[英](Multithreading-Python) How I can create a script that run two scripts which I usually run from two different terminals?
I have two scripts a.py
and b.py
, they send data to each other via a local host (mqtt), and they both depend from a configuration file conf.jso
n.我有两个脚本a.py
和b.py
,它们通过本地主机(mqtt)相互发送数据,它们都依赖于配置文件conf.jso
。 I usually execute them in two different terminals,我通常在两个不同的终端执行它们,
and everything it's OK.一切都很好。 I am trying right now to create another script c.py
which should do the following:我现在正在尝试创建另一个脚本c.py
应该执行以下操作:
config.json
更新config.json
a.py
and b.py
"in two different terminals" “在两个不同的终端”执行a.py
和b.py
a.py
, b.py
and start again with the new parameters关闭a.py
, b.py
并使用新参数重新开始Now, I am very noob about this, so I tried to use Thread from threading现在,我对此非常陌生,所以我尝试使用线程中的线程
from threading import Thread
for parameter in parameter
#update config.json
class exp(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
if self.name == 0:
a.runs()
else:
b.runs()
thread1 = exp(0)
thread1.start()
thread2 = exp(1)
thread2.start()
a.py and b.py scripts both end by: a.py 和 b.py 脚本都以:
def runs():
#whatever runs do
if __name__ = 'main':
runs()
It runs without errors, but it does not work.它运行没有错误,但它不起作用。 I am quite sure there should be a nice and standard solution to this problem.我很确定应该有一个很好的标准解决方案来解决这个问题。 Any ideas?有任何想法吗? Thanks!谢谢!
You probably want multiprocessing
, not the threading
library (look up multiprocessing.Process
. Another fairly equivalent option is to use subprocess.call
to launch the two scripts via shell.您可能需要multiprocessing
,而不是threading
库(查找multiprocessing.Process
。另一个相当等效的选项是使用subprocess.call
通过 shell 启动两个脚本。
Regarding threads - Keep in mind they are limited due to the Global Interpreter Lock in CPython
- which is the prevalent python implementation and the one you probably are using.关于线程 - 请记住,由于CPython
中的全局解释器锁,它们受到限制 - 这是流行的 python 实现,也是您可能正在使用的实现。
So I eventually found this (dirty) solution...any advices for improvements?所以我最终找到了这个(肮脏的)解决方案......有什么改进建议吗?
p = subprocess.Popen(['python', 'random.py']) #initialize a random process just to make sense of the firsts terminate calls in the for cycle.
for parameter in parameters
subprocess.Popen.terminate(p)
#random code
p = subprocess.Popen(['python', 'a.py'])
p = subprocess.call(['python', 'b.py'])
#here I would like to do
#subprocess.Popen.terminate(p)....but it does not work, so I putted the terminate process at the start of the for cycle
I do not totally understand what I wrote but it works fine.我不完全理解我写的内容,但它工作正常。 Thanks everybody for previous tips, and I hope for further explanations.感谢大家之前的提示,我希望进一步的解释。
you can us qt Threading.您可以使用 qt 线程。 Qt has a very powerful library exactly for this purpose. Qt 有一个非常强大的库,正是为此目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.