我正在并行运行两个脚本,如下所示:
import subprocess
from time import sleep
subprocess.Popen(["python3", 'tsn.py'])
subprocess.Popen(["python3", 'lsn.py'])
上面的代码在一个名为 multi.py 的文件中
“tsn.py”和“lsn.py”都使用 file.write() 将数据记录到单独的文本文件中。如果我单独运行 .py 文件,它们会很好地记录数据,但是当我运行 multi.py 时,要记录的数据会很好地打印在我的屏幕上,但不会记录在文本文件中(即 file.write( ) 不执行 )。 问题是什么,我该如何解决?谢谢。
编辑: lsn.py 看起来像这样。 tsn.py 几乎一模一样
from socket import *
import time
serverName_sen = '192.168.0.151'
serverPort_sen = 8080
clientSocket_sen = socket(AF_INET,SOCK_STREAM)
clientSocket_sen.connect((serverName_sen,serverPort_sen))
get='getd'
status='off'
logvar = 0
file = open('lsn_log.txt', 'a')
while 1:
time.sleep(0.5)
clientSocket_sen.send(get.encode('utf-8'))
print('LSN BP1')
#print("get sent")
num = clientSocket_sen.recv(1024)
test=int(num)
print("Data Received from LSN:")
print(test)
if test>210:
if status=='on':
#clientSocket_act.send(off.encode('utf-8'))
status='off'
elif test<100:
if status=='off':
#clientSocket_act.send(on.encode('utf-8'))
status='on'
#The above code simply grabs data from a server
#THE CODE BELOW IS WHAT IS CAUSING THE ISSUE
logvar = logvar+1
if logvar == 5:
print("BP2 LSN")
file.write(time.strftime("%I:%M:%S"))
file.write(" ")
file.write(time.strftime("%d/%m/%Y"))
file.write(" ")
file.write("The Lights are: ")
file.write(status)
file.write(" ")
#file.write(volt)
file.write("\n")
logvar=0
最佳答案
您需要关闭文件或让 with
为您完成:
with open('lsn_log.txt', 'a') as f:
while 1:
time.sleep(0.5)
clientSocket_sen.send(get.encode('utf-8'))
print('LSN BP1')
num = clientSocket_sen.recv(1024)
test = int(num)
print("Data Received from LSN:")
print(test)
if test > 210:
if status == 'on':
#clientSocket_act.send(off.encode('utf-8'))
status = 'off'
elif test < 100:
if status == 'off':
#clientSocket_act.send(on.encode('utf-8'))
status = 'on'
logvar += 1
if logvar == 5:
print("BP2 LSN")
f.write("{} {} The Lights are: {}\n".format(time.strftime("%I:%M:%S"), time.strftime("%d/%m/%Y"), status))
关于python - 从子进程(python,linux)记录数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29181341/