【问题标题】:How to run two python scripts in parallel on Windows如何在 Windows 上并行运行两个 python 脚本
【发布时间】:2014-02-18 04:49:14
【问题描述】:

我目前有两个python脚本,一个用于将数据写入文件,另一个用于同时从该文件连续读取数据并进行绘图。我想创建第三个脚本,它可以同时自动运行这两个脚本(实际上一个稍微领先另一个,因为需要创建文件以便另一个脚本从中读取)。

这是我的代码:

import serial
import sys
import Queue
import threading
import scipy.io
import numpy as num
from mpl_toolkits.mplot3d import *
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import matplotlib.animation as animation
import time
from time import sleep




AngleText = open ("data2.txt" , "w")  # open file for writing data
a= 1
b= 1
c =1

对于范围 (0,20) 内的 x:

count = 0
sleep(0.5)

AngleText.writelines (str(a)+',')
AngleText.writelines (str(b)+',')
AngleText.writelines (str(c)+'\n')

count = count +1
a= a + 1
b= b + 2
c= c + 3
AngleText.flush()

以及绘图脚本:

from mpl_toolkits.mplot3d import *
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import matplotlib
import threading as thrd
import numpy as np

fig = plt.figure()
ax  = fig.add_subplot(111, projection = '3d')
def animate(i):
pullData = open ('data2.txt','r').read()

dataArray = pullData.split('\n')
xar = []
yar = []
zar = []
for eachLine in dataArray:
    if len(eachLine)>1:

        x,y,z = eachLine.split(',')

        xar.append(float(x))
        yar.append(float(y))
        zar.append(float(z))

        tx = xar.pop(0)             
        Floatx= float(tx)
        ty = yar.pop(0)
        Floaty= float(ty)
        tz = zar.pop(0)
        Floatz= float(tz)


        x1 = [164, 94, 0, -100.5]
        x2 = [164, 94, 0, -100.5]
        y1= [-72.5, -103.5, -103.5, -134.5]
        y2= [72.5, 103.5, 103.5, 134.5]
        z1 = [112, 60, 3, 3]
        z2 = [112, 60, 3, 3]


        ax.plot(x1, y1, z1, color = 'b')
        plt.hold(True)
        ax.plot(x2, y2, z2, color = 'r')
        plt.hold(True)
        ax.scatter(Floatx, Floaty, Floatz)
        plt.hold(False)

ani = animation.FuncAnimation(fig,animate, interval = 25)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
ax.set_zlabel('z label')
plt.show()

任何建议将不胜感激!

我目前的解决方案是:

import os
from subprocess import *

import time
from time import sleep


p = Popen([r'testing.py'], shell=True, stdin=PIPE, stdout=PIPE)
output = p.communicate()
print output[0]
sleep(0.5)
#run child script 2
p = Popen([r'realPlot2.py'], shell=True, stdin=PIPE, stdout=PIPE)
output = p.communicate()
print output[0]

通过运行上述代码,直到写入函数完成后才能显示图表。

【问题讨论】:

    标签: multithreading python-2.7


    【解决方案1】:

    使用多处理类。您可以启动一个新进程来写入文件,然后调用 p.join() 使 main 函数等待第一个进程完成,然后启动第二个进程。看这里: http://docs.python.org/2/library/multiprocessing.html

    【讨论】:

    • 好的,这是否意味着我需要将这两个代码合二为一?
    猜你喜欢
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 2019-09-11
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多