繁体   English   中英

从另一个 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 子进程,我可以使用它同时运行这两个进程,但是我无法从子进程 class 中的父进程中捕获任何 output。只需将数据写入文件然后从子进程 class 读取它就可以了但我无法让它可靠地工作,因为它只读了一次; 并关闭文件以再次打开它以阅读似乎太老套和缓慢了。

那么这通常是如何完成的呢? 这是代码的超级简化版本:-

文件 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 this exists 在后台从另一个 Python 代码运行一个 Python 代码,但 pipe 尚未实现,我不确定它是否可以处理列表。

如果将两个文件合并为一个文件的主要问题是阻塞进程,那么将父文件方法作为异步运行 ( https://docs.python.org/3/library/asyncio.html )。 在我看来,将一个文件作为子流程调用并不是 go 转发的最佳方式,因为它解耦了逻辑但保持了依赖性。 如果您需要将文件作为子进程调用,则查看argpase并将列表作为参数传递给

subprocess.run(['python3',file2.py])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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