壳牌和||在python中 [英] shell's && and || in python
问题描述
在shell中,如果我只想在第一个命令成功的情况下执行第二个命令,我就会这样做
In shell if I want to execute a second command only if the first command was successful I would do this
cmd1 && cmd2
如果第一个命令失败,我需要执行第二个命令,我会这样做
And if I need to execute the second command if the first fails I would do this
cmd1 || cmd2
我正在通过python脚本中的subprocess.call调用命令列表.我该怎么做?
I'm calling a list of commands via subprocess.call in a python script. How can I do the above?
推荐答案
将 shell = True
传递给 subprocess.call
,您可以执行任意shell命令.只要确保您正确转义/引用所有内容.
Pass shell=True
to subprocess.call
and you can execute arbitrary shell commands. Just make sure you escape/quote everything correctly.
subprocess.call("true && echo yes!", shell=True)
打印是!
,而
subprocess.call("false && echo yes!", shell=True)
不打印任何内容.
(您无需转义或引用&&
或 ||
,但其中带有空格的文件名可能会很麻烦.)
(You don't need to escape or quote &&
or ||
, but filenames with spaces in them can be a pain.)
这篇关于壳牌和||在python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!