繁体   English   中英

运行 python 脚本并使用来自另一个 python 脚本的 output 文件

[英]running a python script and using its output file from another python script

使用 python 3.6 我在不同的文件夹中有两个 python 脚本。 例如 X/p1.py 和 Y/p2.py p2 创建一个 output 文件(称为 out.txt) 我想从 p1 运行 p2 并使用我从 p1 内部的 p2 获得的 output 文件。 我试过这个:

import subprocess
input_file = subprocess.run(["Y/out.txt"])

代码的 rest 正在重新编辑文件并将其用于创建列表等。 但它没有用,我无法读取文件。 很想听听另一种方式。 谢谢你

使用该指令,您正在尝试运行一个 txt 文件。 除此之外,您确定需要子流程吗? 在p1中导入p2,调用生成out.txt的function还不够吗? 喜欢:

from path_to_p2 import function

def use_output_from_p2():
    function()
    with open ("Y/out.txt","r") as f:
        #do whatever

你想先运行“Y/p2.py”。 然后你想检查 out.txt 文件是否存在并尝试读取它

import subprocess
import os.path

input_file = subprocess.run(["Y/p2.py"])

output_file = "Y/out.txt"
assert os.path.isfile(output_file)

with open(output_file, "r") as output_f:
   ....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM