gpt4 book ai didi

python - 如何通过 subprocess.Popen Python 将多个 linux 命令作为参数序列运行

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:46:26 32 4
gpt4 key购买 nike

代码 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:

ls: cannot access mkdir: No such file or directory
ls: cannot access hello: No such file or directory
2

在上面的代码中,我试图通过将它们作为参数序列传递来运行多个 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 命令。谢谢。

最佳答案

如果某些东西不起作用,请查看其文档: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, ...

关于python - 如何通过 subprocess.Popen Python 将多个 linux 命令作为参数序列运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43883637/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com