简体   繁体   中英

running a python script and using its output file from another python script

using python 3.6 I have two python scripts each in a diffrent folder. eg X/p1.py and Y/p2.py p2 creates an output file (called out.txt) I want to run p2 from p1 and use the output file i got from p2 inside p1. I tried this:

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

rest of the code is reding the file and using it for creating lists and more. But it didnt worked and Im not able to read the file. would love to hear another ways. thank you

With that instruction you are trying to run a txt file. Apart from this are you sure you need subprocess? Isn't it enough to import p2 in p1 and call the function that generates out.txt? Like:

from path_to_p2 import function

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

You want to run "Y/p2.py" first. Then you want to check for the existence of the out.txt file and try to read it

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:
   ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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