为什么我不能在python中读取这个子进程调用的输出?

时间:2017-11-20 09:40:00

标签: python shell subprocess

我想进行子进程调用以获取名为ORIG的文件夹的目录结构。

这是我的代码:

import os
from subprocess import call
# copy the directory structure of ORIG into file

f = open("outputFile.txt","r+b")
call(['find', './ORIG', '-type', 'd'], stdout=f)

a = f.read()
print(a)

调用命令正在运行,因为当我打开它时,我看到文件 outputFile.txt 的内容:

./ORIG
./ORIG/child_one
./ORIG/child_one/grandchild_one
./ORIG/child_two

但为什么我不能读这个/打印输出?

根据Luke.py的建议,我也尝试了以下内容:

import os
import re
from subprocess import call, PIPE

# copy the directory structure of ORIG into file
# make directory structure from ORIG file in FINAL folder

process = call(['find', './ORIG', '-type', 'd'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

if stderr:
    print stderr
else:
    print stdout

这给了我一个问题:

Traceback (most recent call last):
  File "feeder.py", line 9, in <module>
    stdout, stderr = process.communicate()
AttributeError: 'int' object has no attribute 'communicate'

3 个答案:

答案 0 :(得分:2)

首先:无需调用外部程序。如果你想获得某个路径的子目录,那就是python函数os.walk。您可以使用它并使用os.path.isdir检查每个条目,例如使用os.fwalk并使用目录。

如果你真的想调用外部程序并获得它的标准输出,通常高级函数subprocess.run是正确的选择。 你可以通过以下方式获得标准输出:

subprocess.run(command, stdout=subprocess.PIPE).stdout

无需临时文件或低级别功能。

答案 1 :(得分:0)

尝试Popen-

您需要从子流程导入PIPE。

process = subprocess.Popen(['find', './ORIG', '-type', 'd'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()

if stderr:
    print stderr
else:
    print stdout

答案 2 :(得分:0)

如果您不想在写入和读取之间关闭并重新打开文件,可以使用seek命令从头开始读取文件。

import os
from subprocess import call
# copy the directory structure of ORIG into file

f = open("outputFile.txt","r+b")
call(['find', './ORIG', '-type', 'd'], stdout=f)

# move back to the beginning of the file
f.seek(0, 0)

a = f.read()
print(a)