Skip to content Skip to sidebar Skip to footer

Python Pass A Variable To Another Script

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 readabl

Solution 1:

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

defprocess_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 hereiflen(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

Solution 2:

The usual way of passing data from one script to another is to just import the destination function and call it:

# inTool.pyfrom external_script import additional

defwhen_done():
    signal_values = ...        # list referenced by signal_values
    additional(signal_values)  # directly call function in external_script.py

Post a Comment for "Python Pass A Variable To Another Script"