繁体   English   中英

为什么此命令与os.system()一起使用,而不与subprocess.Popen()一起使用?

[英]Why does this command work with os.system() but not subprocess.Popen()?

我想从q中删除许多作业。 删除作业的命令是qdel JOBid

最初,我尝试使用子进程模块,但出现错误:#!/ usr / bin / env python

 import sys, os, subprocess as sp

 lo = sys.argv[1]
 hi = sys.argv[2]

 lo = int(lo)
 hi = int(hi)


for i in range(lo,hi):
    print "i is %d"%i
    p=sp.Popen(['qdel %d'%i],stdout=sp.PIPE)
    #os.system('qdel %d'%i)

所以这没有用。 我得到的错误是

Traceback (most recent call last):
File "del.py", line 14, in <module>
p=sp.Popen(['qdel %d'%i],stdout=sp.PIPE)
File "/usr/lib64/python2.6/subprocess.py", line 639, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

然后,我注释掉了子进程行并使用了os,它立即起作用。 我想我不太了解子流程模块

#!/usr/bin/env python

import sys, os, subprocess as sp

lo = sys.argv[1]
hi = sys.argv[2]

lo = int(lo)
hi = int(hi)


    for i in range(lo,hi):
         print "i is %d"%i
         #p=sp.Popen(['qdel %d'%i],stdout=sp.PIPE)
         os.system('qdel %d'%i)

上面的代码可以完美地工作。 我只想知道子流程模块的原因以及优点。 另外,我正在使用unix shell

您想在Popen调用中使用shell = True。

p=sp.Popen(['qdel %d'%i], shell=True, stdout=sp.PIPE)

如果您阅读manual ,您会发现您对Popen的调用是错误的:您不应传递单个命令,而应传递参数数组:

p=sp.Popen(['qdel', '%d'%i],stdout=sp.PIPE)

另外,正如sc0tt的答案所指出的那样,您可以使用shell=True ,但这在更复杂的情况下有一些缺点:如果命令中包含空格或文件名,则必须手动转义命令中的所有变量数据。任何潜在有害的事物(如;

我也遇到同样的问题。 使用shell = True作为参数之一解决了我的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM