Reputation: 31
I am new to python so my apologies in advance if the question is somewhat dumb or unrealistic.
I have an internally developed tool that converts traces of an ECU to a human readable data with the help of some self-developed python packages that I don’t have access to.
I want to “export” some signal values obtained in this tool (that I can store in a python list in the tool) to an external python script where I can do some additional processing. Something like this: inTool.py
#do some trace processing, get signal_values as a result
def when_done():
start external python script and give it signal_values as input
external_Script.py
#import signal_values from inTool.py and do some additional processing.
Is this doable?
Reason: the tool cannot handle third-party packages well and often crashes. That is why solutions similar to this don’t work for me .
My last resort would probably be to write the values to a text file in the tool and read them out again in my script but I was wondering if there is a nicer way to do it. Thanks!
Upvotes: 0
Views: 924
Reputation: 109
I know this is an older post. I searched for a while for a solid answer and quamrana's response was the best. I'm going to just add to it a little to show a working example.
main.py from other_script import run_this_test
def do_something():
var = "Hello World!"
run_this_test(var)
do_something()
other_script.py
def run_this_test(x):
print(x)
This is my first time posting something like this on here, I know it's basic, but this worked for me!
Upvotes: 0
Reputation: 77347
Writing to an intermediate file is fine, lots of tools do it. You could write your script to use a file or read from its sys.stdin
. Then you have more options on how to use it.
external_script.py
import sys
def process_this(fileobj):
for line in fileobj:
print('process', line.strip())
if __name__ == "__main__":
# you could use `optparse` to make source configurable but
# doing a canned implementation here
if len(sys.argv) == 2:
fp = open(sys.argv[1])
else:
fp = sys.stdin
process_this(fp)
The program could write a file or pipe the data to the script.
import subprocess as subp
import sys
signal_values = ["a", "b", "c"]
proc = subp.Popen([sys.executable, "input.py"], stdin=subp.PIPE)
proc.stdin.write("\n".join(signal_values).encode("utf-8"))
proc.stdin.close()
proc.wait()
You could pipeline through the shell
myscript.py | external_script.py
Upvotes: 3
Reputation: 39374
The usual way of passing data from one script to another is to just import the destination function and call it:
# inTool.py
from external_script import additional
def when_done():
signal_values = ... # list referenced by signal_values
additional(signal_values) # directly call function in external_script.py
Upvotes: 3