OSError: [Errno 13] 权限被拒绝 Python subprocess.call() [英] OSError: [Errno 13] Permission denied Python subprocess.call()
问题描述
我正在尝试在 python 中运行一个子进程,但我收到错误消息:OSError: [Errno 13] 权限被拒绝
I'm trying to run a subprocess in python but I get error message: OSError: [Errno 13] Permission denied
cp2 = cp2.lstrip("~")
cp2 = wilixdirectory+"/Users/"+loggedusr+cp2
if cp3 == None:
subprocess.call([cp2])
else:
subprocess.call([cp2, cp3])
cp2 和 cp3 是目录的用户输入
cp2 and cp3 are user inputs for directories
wilixdirectory 是一个目录
wilixdirectory is a directory
loggedusr 是一个像 "Bob" 或 "Joe" 这样的字符串
loggedusr is a string like "Bob" or "Joe"
代码在 Unix 上用完了
The code is running out of Unix
推荐答案
不要假设路径以斜杠开头,并使用 +
连接,而是使用 os.path.join()
创建路径:
Instead of assuming the path starts with a slash, and concatenating using +
, use os.path.join()
to create the path:
import os.path
basepath = os.path.join(wilixdirectory, 'Users', loggedusr)
cp2 = cp2.lstrip('~/')
cp2 = os.path.abspath(os.path.join(basepath, cp2))
if not cp2.startswith(basepath + os.path.pathsep):
# something is wrong still, the absolute final path is not inside of
# user directory, bail now.
raise ValueError('Not a valid command')
# Perhaps test if os.path.isfile(cp2) is True?
args = [cp2]
if cp3 is not None:
args.append[cp3]
subprocess.call(args)
请注意,我从 cp2
的开头去除了 ~
和 /
以从用户输入中删除任何意外的开始字符,然后使用os.path.abspath()
以确保路径是规范路径,并且解析了任何 ./
和 ../
条目.您做然后需要验证最终结果是否仍在用户的目录中,而不是在用户目录之外.
Note that I strip ~
, and /
from the start of cp2
to remove any accidental start characters from the user input, then use os.path.abspath()
to make sure the path is a canonical path, with any ./
and ../
entries resolved. You do then need to verify that the final result is still within the users' directory and not outside of it.
在运行 subprocess.call() 之前,您可以使用
os.path.isfile()
进行测试以查看 cp2
路径是否实际指向实际文件代码>.
You could test with os.path.isfile()
to see if the cp2
path actually points to an actual file before running subprocess.call()
.
这篇关于OSError: [Errno 13] 权限被拒绝 Python subprocess.call()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!