Popen错误:[Errno 2]没有这样的文件或目录

2024-09-28 21:33:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些自定义命令。

# works 
subprocess.Popen(['python'], stdout=subprocess.PIPE)

但是如果我有自己的系统命令,比如deactivate,我就会得到这个错误

Traceback (most recent call last):
  File "runner2.py", line 21, in <module>
    main() 
  File "runner2.py", line 18, in main
    subprocess.Popen(['deactivate',], stdout=subprocess.PIPE)
  File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
    errread, errwrite)
  File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

更不用说我需要在沙箱virtualenv下执行这个。


Tags: inpy命令childmainlibusrstdout
3条回答

尝试在Popen调用中添加额外的参数'shell=True'。

您必须给出程序deactivate的完整路径,然后子流程模块应该能够找到它。

只是个便条。shell=True可能是o.p的正确解决方案,因为它们没有犯下以下错误,但是如果不将可执行文件与其参数分离,也可能会出现“No such file or directory”错误。

import subprocess as sp, shlex
sp.Popen(['echo 1']) # FAILS with "No such file or directory"
sp.Popen(['echo', '1']) # SUCCEEDS
sp.Popen(['echo 1'], shell=True) # SUCCEEDS, but extra overhead
sp.Popen(shlex.split('echo 1')) # SUCCEEDS, equivalent to #2

如果没有shell=True,Popen希望可执行文件是args的第一个元素,这就是它失败的原因,没有“echo 1”可执行文件。添加shell=True将调用系统shell并将args的第一个元素传递给shell。i、 e.对于linux,Popen(['echo 1'], shell=True)相当于Popen('/bin/sh', '-c', 'echo 1'),这比您可能需要的开销要多。有关shell=True实际有用的情况,请参见Popen() documentation

相关问题 更多 >