首页 > 解决方案 > 当我尝试使用子进程打开/访问文件时拒绝访问

问题描述

这是我第一次写问题,如果我做错了,请见谅。

我编写了这个示例代码来显示错误,并且我在 Windows 上运行:

import subprocess as sp
inp = sp.run(['find', '/n', '"es"', 'test.txt'], shell=True, capture_output=True, text= True)
print(inp.stdout)
print(inp.returncode)
print(inp.stderr)

*“test.txt”文件包含以下内容:

that is a test
jeje
end

输出:

---------- TEST.TXT

1

Access is denied: \

当我find /n "je" test.txt直接在 CMD 中运行时没有问题。我想它可能与任何类型的管理权限有关......所以我以管理员身份运行 VSCode,但没有办法。我在互联网上没有发现类似的错误。提前致谢。

标签: pythonsubprocess

解决方案


如果你尝试使用怎么样os.popen

import os

inp = os.popen('find /n "es" test.txt')
print(inp.read())

subprocess 在这种情况下似乎不起作用,因此您可能喜欢上述解决方法。此外,如果您尝试查找的文件在其名称中包含空格,则替换test.txt"some big file name.txt"


推荐阅读