贝壳&&和||在python中

时间:2012-09-14 10:19:34

标签: python shell command

在shell中,如果我只想在第一个命令成功时执行第二个命令,我会这样做

cmd1 && cmd2

如果我需要执行第二个命令,如果第一个命令失败,我会这样做

cmd1 || cmd2

我在python脚本中通过subprocess.call调用命令列表。我怎么能做到这一点?

3 个答案:

答案 0 :(得分:5)

shell=True传递给subprocess.call,您可以执行任意shell命令。请确保escape/quote everything correctly

subprocess.call("true && echo yes!", shell=True)

打印yes!,而

subprocess.call("false && echo yes!", shell=True)

什么都不打印。

(您无需转义或引用&&||,但其中包含空格的文件名可能会很痛苦。)

答案 1 :(得分:1)

这种东西会起作用

In [227]: subprocess.Popen(['dir', '||', 'ls'], shell=True)
Out[227]: <subprocess.Popen at 0x1e4dfb0>

 Volume in drive D has no label.
 Volume Serial Number is 4D5A-03B6

 Directory of D:\Dummy

09/14/2012  03:54 PM    <DIR>          .
09/14/2012  03:54 PM    <DIR>          ..
               0 File(s)              0 bytes
               2 Dir(s)  141,482,524,672 bytes free

In [228]: subprocess.Popen(['dir', '&&', 'ls'], shell=True)
Out[228]: <subprocess.Popen at 0x1e4df10>
 Volume in drive D has no label.
 Volume Serial Number is 4D5A-03B6

 Directory of D:\Dummy

09/14/2012  03:54 PM    <DIR>          .
09/14/2012  03:54 PM    <DIR>          ..
               0 File(s)              0 bytes
               2 Dir(s)  141,482,524,672 bytes free
'ls' is not recognized as an internal or external command,
operable program or batch file.

答案 2 :(得分:1)

扩展@larsmans回答 - 如果您使用的是subprocess.call,并且由于某种原因不想设置shell=True,则可以检查returncode属性。
如果返回码为0,则命令成功。您还可以实施subprocess.check_call来筹集CalledProcessError。这是一些有用的documentation

相关问题