从子进程 (python,linux) 记录数据

Logging data from a subprocess (python,linux)

我运行并行执行两个脚本如下:

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))