在单独运行的 Python 脚本之间传递数据 [英] Passing data between separately running Python scripts

查看:74
本文介绍了在单独运行的 Python 脚本之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个正在运行的 python 脚本(带有完整的 Tkinter GUI 和所有东西)并且我想将它正在收集的实时数据(内部存储在数组等中)传递给另一个 python 脚本,那么最好的方法是什么那个?

If I have a python script running (with full Tkinter GUI and everything) and I want to pass the live data it is gathering (stored internally in arrays and such) to another python script, what would be the best way of doing that?

我不能简单地将脚本 A 导入脚本 B,因为它会创建脚本 A 的新实例,而不是访问已经运行的脚本 A 中的任何变量.

I cannot simply import script A into script B as it will create a new instance of script A, rather than accessing any variables in the already running script A.

我能想到的唯一方法是让脚本 A 写入文件,然后脚本 B 从文件中获取数据.这不太理想,但是如果脚本 B 尝试读取脚本 A 已经写入的文件,可能会发生一些不好的事情.此外,我正在寻找两个程序之间更快的通信速度.

The only way I can think of doing it is by having script A write to a file, and then script B get the data from the file. This is less than ideal however as something bad might happen if script B tries to read a file that script A is already writing in. Also I am looking for a much faster speed to communication between the two programs.

以下是要求的示例.我知道为什么这不起作用,但这是需要实现的基本前提.我的源代码很长,不幸的是机密,所以在这里没有帮助.总之,脚本 A 正在运行 Tkinter 并收集数据,而脚本 B 是作为 Django 一部分的 views.py,但我希望这可以作为 Python 的一部分来实现.

Here are the examples as requested. I am aware why this doesn't work, but it is the basic premise of what needs to be achieved. My source code is very long and unfortunately confidential, so it is not going to help here. In summary, script A is running Tkinter and gathering data, while script B is views.py as a part of Django, but I'm hoping this can be achieved as a part of Python.

脚本 A

import time

i = 0

def return_data():
    return i

if __name__ == "__main__":
    while True:
        i = i + 1
        print i
        time.sleep(.01)

脚本 B

import time
from scriptA import return_data

if __name__ == '__main__':
    while True:
        print return_data()  # from script A
        time.sleep(1)

推荐答案

您可以使用 multiprocessing 模块在两个模块之间实现一个 Pipe.然后,您可以将其中一个模块作为进程启动,并使用管道与其进行通信.使用管道最好的部分是您还可以通过它传递诸如 dict、list 之类的 Python 对象.

you can use multiprocessing module to implement a Pipe between the two modules. Then you can start one of the modules as a Process and use the Pipe to communicate with it. The best part about using pipes is you can also pass python objects like dict,list through it.

例如:mp2.py:

from multiprocessing import Process,Queue,Pipe
from mp1 import f

if __name__ == '__main__':
    parent_conn,child_conn = Pipe()
    p = Process(target=f, args=(child_conn,))
    p.start()
    print(parent_conn.recv())   # prints "Hello"

mp1.py:

from multiprocessing import Process,Pipe

def f(child_conn):
    msg = "Hello"
    child_conn.send(msg)
    child_conn.close()

这篇关于在单独运行的 Python 脚本之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆