Python3:os系统捕获读取/写入文件

问题描述 投票:0回答:1

我正在编写一个需要使用第三方shell脚本的应用程序。

这个shell脚本some-script处理输入文件--ifile并将结果保存在输出文件--ofile中。

所以目前我可以写/读到tmp文件并在之后删除它们

import os

ifile_name = '/tmp/ifile.txt'
ofile_name = '/tmp/ofile.txt'

with open(ifile_name, 'w') as f:
    # write data to ifile for 'some-script'


# format command
command = 'some-script --ifile {ifile} --ofile {ofile}'.format(
    ifile=ifile_name,
    ofile=ofile_name
)

os.system(command)

with open(ofile_name, 'r') as f:
    # read in data from ofile

# clean up and delete tmp files

有没有办法可以直接将python数据传递给--ifile(例如通过'\n'.join(arr))并将--ofile流结果作为脚本返回而无需读取/写入文件?只是字符串解析?

python python-3.x subprocess
1个回答
0
投票

该脚本将其输出返回到stdout,py脚本将通过PIPE读取它

with Popen(["your_script_here"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
© www.soinside.com 2019 - 2024. All rights reserved.