简体   繁体   English

在没有线程的情况下并发执行python脚本

[英]python script execution in concurrently without thread

How can I execute single python script multiple time concurrently using different PID without using Threads and Multiprocessing from another python script? 如何使用不同的PID同时执行单个python脚本多次,而又不使用其他python脚本中的Threads和Multiprocessing?

And I need to get results from each execution 我需要从每次执行中获取结果

I tried Multiprocessing module simple program I got AttributeError: 'module' object has no attribute 'f' and it need to work on both Linux and windows. 我尝试了多处理模块简单程序,但得到了AttributeError: 'module' object has no attribute 'f' ,它需要在Linux和Windows上都可以工作。 previous post's solution not working for me 以前的帖子的解决方案对我不起作用

After verifying with previous posts I posted this again. 经过先前的帖子验证后,我再次发布了此帖子。

A different PID means you need a different process. 不同的PID意味着您需要不同的过程。 Not using multiprocessing you may start another process with the subprocess module and get the result via stdout : 不使用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 needs to write the result serialized with pickle to its stdout . test.py需要将用pickle序列化的结果写入其stdout

May this help? 这可以帮助吗?

test.py:(just for demo) 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)

Run it several times: 运行几次:

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

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM