提问人:Thugunb 提问时间:12/29/2022 更新时间:12/29/2022 访问量:26
从另一个 Python 文件启动 Python 文件,然后在它们同时运行时在它们之间发送数据的最简单方法是什么?
What is the easiest way to launch a Python file from another Python file then send data across them while they run simultaneously?
问:
我想首先运行一个 python 文件(父文件),它会自动执行另一个 python 文件(子文件)并将数据(特别是列表)从父文件发送到子文件。
我无法将一个文件导入到另一个文件,因为父文件必须执行大量阻塞命令,并且我需要子文件连续发布。
我最初尝试了 Popen 子进程,我能够同时运行这两个子进程,但我无法从子类中的父类中捕获任何输出。简单地将数据写入文件,然后从子类中读取数据可以工作,但我无法让它可靠地工作,因为它只读取一次;关闭文件以再次打开它进行阅读似乎太笨拙和缓慢。
那么这通常是如何做到的呢?这是代码的超简化版本:-
文件 1(父文件):-
list = [0,0,0]
class CmdDecide:
def __init__(self, param1=50):
//Some code
//I tried subprocess.run(['python3',file2.py]) to run the 2 files simultaneously but I need to send the list variable to it
def func_A(self, var_from_someplace_else):
global list
list = var_from_someplace_else
sendList(list)
def sendList(self):
//Code to send this list to file 2 somehow
//There are a lot more functions in this file
文件 2(子文件):-
def main():
//Send continuous output [0,0,0] till File 1 changes the array
//It will continuously output the new array and continue to do so till the program is terminated
注意:Ik 这存在从另一个 Python 代码在后台运行一个 Python 代码,但管道尚未实现,我不确定它是否可以处理列表。
答:
0赞
m-eriksen
12/29/2022
#1
如果将两个文件合并为一个文件的主要问题是阻塞进程,则以异步 (https://docs.python.org/3/library/asyncio.html) 方式运行父文件方法。在我看来,将一个文件作为子进程调用并不是最好的前进方式,因为它解耦了逻辑,但保持了依赖关系。 如果您需要将文件作为子进程调用,请查看 argpase 并将列表作为参数传递给
subprocess.run(['python3',file2.py])
评论