【问题标题】:issue in using subprocess to execute two process simultaneously使用子进程同时执行两个进程的问题
【发布时间】:2015-05-03 06:13:57
【问题描述】:

我正在尝试使用 subprocess 从 python 脚本中执行 python 脚本,但我遇到了某些问题。这是我想做的:

我想先启动一个主进程(执行 python 脚本 1),然后在执行该进程一段时间后,我想启动一个子进程(执行 python 脚本 2)。现在,当这个子进程正在执行时,我希望主进程的执行也会继续,当主进程完成时,它应该等待子进程完成。

下面是我写的代码。这里Script1.py 是我导入到我的代码中的主进程脚本。 Script2.py 是使用subprocess.Popen() 调用的子进程脚本。

Script1.py

import time

def func():
    print "Start time : %s" % time.ctime()
    time.sleep( 2 )
    print "End time: %s" % time.ctime()
    return 'main process'

Script2.py

import time

def sub():
    count=0
    while count < 5:
        print "Start time : %s" % time.ctime()
        time.sleep(3)
        print "End time: %s" % time.ctime()
        x+=1
    return 'sub process'

if __name__ == '__main__':
   print 'calling function inside sub process'
   subval = sub()

Main_File.py 是通过导入Script1.py 启动第一个进程的脚本,然后稍后也启动子进程

Main_file.py

import subprocess
import sys
import Script1

def func1():

    count=0

    while x < 5:
        code = Script1.func()

        if x == 2:
            print 'calling subprocess'
            sub_result = subprocess.Popen([sys.executable,"./Script2.py"]) # Start the execution of sub process. Main process should keep on executing simultaneously
        x+=1
    print 'Main process done'
    sub_result.wait() # even though main process is done it should wait for sub process to get over
    code = sub_result # Get the value of return statement from Sub process
    return code


if __name__ == '__main__':
    print 'starting main process'
    return_stat = func1()
    print return_stat

当我运行Main_file.py 时,它执行的输出不正确。似乎它没有执行子进程,因为我没有看到任何用 Script2.py 编写的打印语句,并且它在主进程完成后停止。此外,我不确定从子流程中获取 return 语句值的方式。任何人都可以帮助我尝试获得正确的输出。

注意:我是 python 和子进程的新手,所以我先代表我尝试。对概念有不理解的地方还请见谅

【问题讨论】:

标签: python subprocess


【解决方案1】:

子进程调用外部程序。您的 Script2 不执行任何操作,因为未调用函数 sub。也许您想使用线程:

import threading
import Script1
import Script2

def func():
    thread1 = threading.Thread(target=Script1.func)
    thread1.start()
    thread2 = threading.Thread(target=Script2.sub)
    thread2.start()
    thread2.wait()

【讨论】:

  • 是否可以通过subprocess 来实现,因为它是在应用程序中通用的要求?
  • 你应该在最后加上if __name__=="__main__": func()
  • @J.F.Sebastian 在哪个脚本的末尾我应该提到这一点?我在Script2.py 的末尾添加了if __name__=="__main__": ,并从那里调用了sub()Script1.py 也一样。另外如何从 Script2.py 函数(子进程)获取返回值?
  • 如果您按照@Daniel 的答案运行代码,那么它只会导入模块并定义函数。它实际上并没有运行它。仅当您希望将脚本作为程序运行并将其导入另一个脚本时,您才需要 __main__ 保护。 __main__ 部分应位于您希望作为程序运行的文件中。
  • @J.F.Sebastian 感谢您的解释。如何从子进程(Scrip2.py)中获取return语句的值?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
相关资源
最近更新 更多