This question already has answers here:
Store output of subprocess.Popen call in a string

(15个答案)


2年前关闭。




我想从python脚本中的一些shell命令(如lsdf)获取输出。我看到不推荐使用commands.getoutput('ls'),但是subprocess.call('ls')只会为我提供返回码。

我希望有一些简单的解决方案。

最佳答案

使用子进程。打开:

import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)

请注意,通信将阻塞,直到进程终止。如果在终止输出之前需要输出,则可以使用 process.stdout.readline()。有关更多信息,请参见documentation

关于python - 子过程中的python getoutput()等效项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6657690/

10-12 16:55
查看更多