【问题标题】:Send changing counter int variable to another python script concurrently同时将更改的计数器 int 变量发送到另一个 python 脚本
【发布时间】:2020-12-30 13:31:33
【问题描述】:

我有两个 python 脚本,script1.py 和 script2.py。一个是独立递增int x 的计数器,script2.py 是每5 秒取一次int x 的值,输入到script2.py 中。我已经尝试使用以下帖子中的多处理逐字执行此操作,

Passing data between separately running Python scripts

我为 script1 应用了 While True 函数。这是我的尝试,但我认为我不理解一般想法并且我遇到了各种错误,因为我是 python 新手,我错过了一些细节。

script1.py:

from multiprocessing import Process, Pipe
x = 0

def function(child_conn):
    global x
    while True:
         x += 1
         print(x)
         child_conn.send(x)
         child_conn.close()

script2.py:

from multiprocessing import Proces,Queue,Pipe
from script1 import function
from time import sleep

if __name__=='__main__':
    parent_conn,child_conn = Pipe()
    p = Process(target=function, args=(child_conn,))
    p.start()
    print(parent_conn.recv())
    time.sleep(5)

提前致谢!

【问题讨论】:

  • 您引用的帖子只有部分代码。试试这个帖子:stackoverflow.com/questions/7749341/…
  • @Mike67 那篇文章是关于套接字的。我错过了什么吗?
  • @Lactobacillus 您能否更明确地说明您的错误,以便我们更好地帮助您。

标签: python variables multiprocessing


【解决方案1】:

您在子进程中有一个循环,但在父进程中没有循环。没有循环,孩子只能发送一条消息然后抛出错误。

试试这个代码。运行 script2.py 启动进程。

script1.py

from multiprocessing import Process, Pipe
from time import sleep
x = 0

def function(child_conn):
    global x
    while True:
         x += 1
         print(x)
         child_conn.send(x)
         #child_conn.close()
         sleep(1)

script2.py

from multiprocessing import Process,Queue,Pipe
from script1 import function
from time import sleep

if __name__=='__main__':
    parent_conn,child_conn = Pipe()
    p = Process(target=function, args=(child_conn,))
    p.start()
    while True:
        print(parent_conn.recv())
    sleep(1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-25
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多