Python Popen拒绝运行命令,即使os.system工作正常
每当我运行此脚本时:Python Popen拒绝运行命令,即使os.system工作正常,python,gruntjs,subprocess,popen,Python,Gruntjs,Subprocess,Popen,每当我运行此脚本时: import subprocess process = subprocess.Popen(['grunt', 'build'], stdout=subprocess.PIPE) 我经常会遇到这样的错误: Traceback (most recent call last): File "test_grunt_fail.py", line 3, in <module> process = subprocess.Popen(['grunt', 'bui
import subprocess
process = subprocess.Popen(['grunt', 'build'], stdout=subprocess.PIPE)
我经常会遇到这样的错误:
Traceback (most recent call last):
File "test_grunt_fail.py", line 3, in <module>
process = subprocess.Popen(['grunt', 'build'], stdout=subprocess.PIPE)
File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
回溯(最近一次呼叫最后一次):
文件“test\u grunt\u fail.py”,第3行,在
process=subprocess.Popen(['grunt','build'],stdout=subprocess.PIPE)
文件“C:\Python27\lib\subprocess.py”,第710行,在_init中__
错误读取,错误写入)
文件“C:\Python27\lib\subprocess.py”,第958行,在执行子进程中
startupinfo)
WindowsError:[错误2]系统找不到指定的文件
但是,grunt
是绝对安装的,因为我可以从命令行运行grunt build
,也可以在程序内部运行os.system(“grunt build”)
既然如此,为什么
os.system()
可以工作,而subprocess.Popen()
不能工作?可能重复的@aruistante不是该答案的重复(事实上,我先看了这个答案);注意到OP试图运行的是一个别名,这个问题就解决了。但是,在本例中,grunt
肯定是系统路径上某个对象的名称(grunt.bat
),而不是别名。我大约在一年前询问过。我认为注释中的cwd
关键字参数起作用了。@Blender谢谢-我没有读过这个。不过,这可能不适用:引用对您的问题的评论,“在Windows上指定shell=True的唯一时间是当您希望执行的命令内置到shell中时(例如dir或copy)。您不需要shell=True来运行批处理文件或基于控制台的可执行文件。”@Blender在添加cwd
后,错误变为“Users\John\AppData\Roaming\npm\node\u modules\grunt cli\bin\grunt”)语法错误:(unicode错误)“UnicodeScape”编解码器无法解码位置2-3的字节:截断\UXXXXXXXX转义”