我想使用 os.system 运行命令,但出现错误
c:/fe ' is not recognized as an internal or external command, operable program or batch file
我使用的代码是
import os
os.system('"C:\\fe re\\python.exe" program "c:\\test now\\test.txt" http://site.to.explore')
如果我只运行它就会起作用:
import os
os.system('"C:\\fe re\\python.exe" program -h')
或者如果我像这样的Python路径中没有空间
import os
os.system('C:\\fere\\python.exe program "c:\\test now\\test.txt" http://site.to.explore')
但是如果我在 python 路径和 txt 路径中的命令中有两对双引号,我会收到错误...
os.system
有一些严重的缺点,尤其是文件名和 w.r.t 中的空格。安全。我建议您研究 subprocess
模块,特别是 subprocess.check_call,它更强大。然后你可以做例如
import subprocess
subprocess.check_call(["c:\\fe re\\python.exe", "program", etcetc...])
当然,请确保非常小心,不要在这些调用中使用用户确定的变量,除非用户已经使用相同的权限从命令行运行脚本。
我不同意
subprocess
模块是公认的答案。
我可以用任何其他语言对系统进行相同的调用,并且不会出现任何问题。这在Python中被破坏了。
这是我解决这个问题的简单解决方案:
os.chdir("C:\\Program Files\\7-Zip")
os.system("7z.exe e \"{}\" -o\"{}\"\n".format(os.path.join(directory, file), self.out))
您只需更改为可执行文件的目录,然后照常运行
os.system
命令即可。
很抱歉提出一个旧线程,但我如何访问 locallow 文件夹?