为什么此命令适用于 os.system() 而不适用于 subprocess.Popen()? [英] Why does this command work with os.system() but not subprocess.Popen()?

查看:39
本文介绍了为什么此命令适用于 os.system() 而不适用于 subprocess.Popen()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 q 中删除一些作业.删除作业的命令是qdel JOBid.

I want to delete a number of jobs from a q. The command to delete the job is qdel JOBid.

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

Initially, I tried to use the subprocess module, but I got an error: #!/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)

所以这不起作用.我得到的错误是

So this did not work. The error I got was

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

然后我注释掉 subprocess 行并使用 os 并且它立即起作用.我想我没有完全理解子流程模块

Then I commented out the subprocess line and used os and it worked immediately. I think I don't fully understand the subprocess module

#!/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)

上面的代码完美无缺.我只想知道 subprocess 模块的原因和优势是什么.另外,我使用的是 unix shell

The above code worked flawlessly. I just want to know why and what the advantages are of the subprocess module. Also, I am using a unix shell

推荐答案

如果你阅读了 manual,你可以看到你对 Popen 的调用是错误的:你不应该传递一个命令,而是一个参数数组:

If you read manual, you can see that your call to Popen is wrong: you should pass not a single command, but an array of arguments:

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

或者,正如 sc0tt 的答案 指出的那样,您可以使用 shell=True,但是这在更复杂的情况下有一些缺点:您必须手动转义命令中的所有变量数据,以防它包含例如带空格的文件名或任何更可能有害的内容(如 ;)

Alternatively, as sc0tt's answer points out, you can use shell=True, but this has some disadvantages in more complex cases: you would have to manually escape all the variable data in the command in case it contains, for example, filenames with spaces or anything much more potentially harmful (like ;)

这篇关于为什么此命令适用于 os.system() 而不适用于 subprocess.Popen()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆