记录来自子进程的数据(python、linux)

2024-09-28 23:01:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我并行运行两个脚本,如下所示:

import subprocess
from time import sleep
subprocess.Popen(["python3", 'tsn.py'])
subprocess.Popen(["python3", 'lsn.py'])

上面的代码在一个名为多.py你知道吗

两者都是tsn.py公司'和'lsn.py公司'将数据记录到单独的文本文件中文件.write(). 如果我单独运行.py文件,它们会很好地记录数据,但是当我运行多.py要记录的数据在我的屏幕上打印得很好,但它不会记录在文本文件中(即文件.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

Tags: frompyimporttimestatus记录公司file
1条回答
网友
1楼 · 发布于 2024-09-28 23:01:58

您需要关闭文件或让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))

相关问题 更多 >