我想用 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...])
当然,请确保非常小心,不要在这些调用中使用用户确定的变量,除非用户已经使用相同的权限从命令行自己运行脚本。
关于python - 如何从 python 执行程序?操作系统失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27662536/