【问题标题】:python script execution in concurrently without threadpython脚本在没有线程的情况下同时执行
【发布时间】:2016-01-20 12:02:44
【问题描述】:

如何在不使用另一个 python 脚本的线程和多处理的情况下使用不同的 PID 同时执行单个 python 脚本?

我需要从每次执行中获取结果

我尝试了多处理模块简单程序,我得到了AttributeError: 'module' object has no attribute 'f',它需要在 Linux 和 Windows 上运行。上一篇文章的解决方案对我不起作用

在与之前的帖子核实后,我再次发布了这个。

【问题讨论】:

  • 尝试运行“python yourscript.py >> output.txt &”几次??我正在测试这个。您可以在脚本中打印 pid。
  • 最好在脚本中写入某个文件而不是“>> output.txt”。如果这符合您的要求,我会提供详细的答复。
  • 为什么multiprocessing.Process没有选项?

标签: python python-multithreading python-multiprocessing


【解决方案1】:

不同的 PID 意味着您需要不同的进程。如果不使用multiprocessing,您可以使用subprocess 模块启动另一个进程并通过stdout 获得结果:

#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_function
import pickle
import sys
from subprocess import PIPE, Popen


def main():
    processes = [
        Popen([sys.executable, 'test.py'], stdout=PIPE)
        for _ in xrange(5)
    ]
    results = [pickle.loads(p.stdout.read()) for p in processes]
    for process in processes:
        process.wait()
    print(results)


if __name__ == '__main__':
    main()

test.py需要将pickle序列化的结果写入其stdout

【讨论】:

    【解决方案2】:

    这有帮助吗?

    test.py:(仅用于演示)

    import time, os, datetime, fcntl
    
    with open("output.txt", "a") as g:
        fcntl.flock(g, fcntl.LOCK_EX)
        g.write( "PID [" + str(os.getpid()) + "]," + str(datetime.datetime.now()) + "\n" )
        fcntl.flock(g, fcntl.LOCK_UN)
    
    
    time.sleep(30)
    
    with open("output.txt", "a") as g:
        fcntl.flock(g, fcntl.LOCK_EX)
        g.write( "PID [" + str(os.getpid()) + "]," + str(datetime.datetime.now()) + "\n" )
    fcntl.flock(g, fcntl.LOCK_UN)
    

    运行几次:

    c@chen:~/src$ python test2.py &
    [1] 29265
    c@chen:~/src$ python test2.py &
    [2] 29266
    c@chen:~/src$ python test2.py &
    [3] 29268
    c@chen:~/src$ python test2.py &
    [4] 29269
    c@chen:~/src$ vim test2.py 
    [1]   Done                    python test2.py
    [2]   Done                    python test2.py
    [3]-  Done                    python test2.py
    [4]+  Done                    python test2.py
    

    输出:

    c@chen:~/src$ tail -f -n 100 output.txt 
    PID [29265],2016-01-20 16:28:20.373244
    PID [29266],2016-01-20 16:28:21.068946
    PID [29268],2016-01-20 16:28:21.911043
    PID [29269],2016-01-20 16:28:22.547805
    PID [29265],2016-01-20 16:28:50.403474
    PID [29266],2016-01-20 16:28:51.075268
    PID [29268],2016-01-20 16:28:51.914001
    PID [29269],2016-01-20 16:28:52.564706
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 2018-12-10
      • 2016-04-17
      • 2017-04-03
      相关资源
      最近更新 更多