如何以参数序列的形式运行多个linux命令子流程.PopenPython

2024-06-25 06:46:50 发布

您现在位置:Python中文网/ 问答频道 /正文

代码1:以参数序列的形式传递linux命令

from subprocess import Popen, PIPE

run_cmd = Popen(['ls','-l','mkdir','hello'], stdout = PIPE, stderr = PIPE)
output,error = run_cmd.communicate()
print error,output, run_cmd.returncode

输出-1:

^{pr2}$

在上面的代码中,我尝试运行多个linux命令,方法是将它们作为参数序列传递。如果我把上面的代码修改为下面的代码,它可以正常工作。在

代码2:将linux命令作为字符串传递

from subprocess import Popen, PIPE

run_cmd = Popen('mkdir hello; ls -l; echo Hello; rm -r hello', shell=True, stdout = PIPE, stderr = PIPE)
output,error = run_cmd.communicate()
print error,output, run_cmd.returncode

输出-2:

drwxrwxr-x. 2 sujatap sujatap    6 May  9 21:28 hello
-rw-rw-r--. 1 sujatap sujatap   53 May  8 20:51 test.py
Hello
0

由于shell=True不是建议使用的方法,所以我想使用前一种方法运行linux命令。谢谢。在


Tags: 方法run代码from命令cmdhellooutput
1条回答
网友
1楼 · 发布于 2024-06-25 06:46:50

如果有什么不起作用,请检查它的文档:https://docs.python.org/2/library/subprocess.html#popen-constructor

args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

因此,首先测试您的单个程序的运行情况(程序及其参数的列表),然后列出一个列表,并使用循环按顺序运行它们:

myprogramsequence = [
    ["ls", "-l"],
    ["mkdir", "hello"]
]

for argumentlist in myprogramsequence:
    run_cmd = Popen( argumentlist, ...

相关问题 更多 >