use*_*451 45 python subprocess popen
我有一些自定义命令.
# works
subprocess.Popen(['python'], stdout=subprocess.PIPE)
Run Code Online (Sandbox Code Playgroud)
但是,如果我有自己的系统命令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
Run Code Online (Sandbox Code Playgroud)
更别说我需要在我的沙箱virtualenv下执行此操作.
Ant*_*ong 99
尝试在Popen
调用中添加额外的参数'shell = True' .
Mar*_*ard 35
只是一张纸条.shell=True
可能是op的正确解决方案,因为它们没有出现以下错误,但如果不从参数中拆分可执行文件,也可以获得"无此文件或目录"错误.
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
Run Code Online (Sandbox Code Playgroud)
没有shell=True
,Popen希望可执行文件是args的第一个元素,这就是它失败的原因,没有"echo 1"可执行文件.添加shell=True
调用系统shell并将第一个元素传递args
给shell.即对于Linux,Popen(['echo 1'], shell=True)
相当于Popen('/bin/sh', '-c', 'echo 1')
你可能需要的开销更大.有关实际有用的案例,请参阅Popen()文档shell=True
.
归档时间: |
|
查看次数: |
57149 次 |
最近记录: |