Python 将变量传递给另一个脚本 [英] Python pass a variable to another script
问题描述
我是 Python 新手,所以如果问题有点愚蠢或不切实际,我提前道歉.
I am new to python so my apologies in advance if the question is somewhat dumb or unrealistic.
我有一个内部开发的工具,可以借助一些我无法访问的自行开发的 Python 包将 ECU 的痕迹转换为人类可读的数据.
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.
我想将在这个工具中获得的一些信号值(我可以存储在工具的 python 列表中)导出"到一个外部 python 脚本,在那里我可以做一些额外的处理.像这样的东西:在Tool.py中
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
external_Script.py
#import signal_values from inTool.py and do some additional processing.
这可行吗?
原因:该工具不能很好地处理第三方包,经常崩溃.这就是为什么解决方案类似于这个 不适合我.
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!
推荐答案
写入中间文件很好,很多工具都可以做到.您可以编写脚本以使用文件或从其 sys.stdin
中读取.然后你有更多关于如何使用它的选择.
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
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()
你可以通过 shell 管道
You could pipeline through the shell
myscript.py | external_script.py
这篇关于Python 将变量传递给另一个脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!