【问题标题】:How to run two python scripts simultaneously from a master script如何从主脚本同时运行两个 python 脚本
【发布时间】:2018-06-22 04:23:00
【问题描述】:

我有两个处于无限循环中的独立脚本。我需要从另一个主脚本调用它们并让它们同时运行。同时产生结果。

这里有一些脚本

script1.py

y= 1000000000
while True:
      y=y-1
      print("y is now: ", y)

script2.py

x= 0
while True:   
   x=x+1
   print("x is now: ", x)

目的是用pyinstaller将主脚本编译到一个控制台中

【问题讨论】:

  • 你也能写出预期的输出吗

标签: python multithreading


【解决方案1】:

您可以使用 python 'multiprocessing' 模块。

import os
from multiprocessing import Process

def script1:
    os.system("script1.py")     
def script2:
    os.system("script2.py") 

if __name__ == '__main__':
    p = Process(target=script1)
    q = Process(target=script2)
    p.start()
    q.start()
    p.join()
    q.join()

请注意,print 语句可能不是检查进程并行性的准确方法。

【讨论】:

    【解决方案2】:

    Python 脚本在导入时执行。 因此,如果您真的想保持两个脚本不受影响,您可以在单独的过程中导入每个脚本,如下所示。

    from threading import Thread
    
    
    def one(): import script1
    def two(): import script2
    
    Thread(target=one).start()
    Thread(target=two).start()
    

    如果您想要两个进程而不是线程,则类似:

    from multiprocessing import Process
    
    
    def one(): import script1
    def two(): import script2
    
    Process(target=one).start()
    Process(target=two).start()
    

    【讨论】:

      【解决方案3】:

      将脚本的代码包装在函数中以便可以导入。

      def main():
          # script's code goes here
          ...
      

      使用“if main”来保持作为脚本运行的能力。

      if __name__ == '__main__':
          main()
      

      使用多处理或线程来运行创建的函数。

      如果你真的不能让你的脚本可导入,你总是可以使用 subprocess 模块,但是运行器和你的脚本之间的通信(如果需要的话)会更复杂。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-19
        • 2019-11-21
        • 1970-01-01
        • 2022-12-10
        • 2021-03-18
        • 1970-01-01
        • 2015-02-18
        • 2020-02-19
        相关资源
        最近更新 更多