mrsinister
mrsinister

Reputation: 97

Logging data from a subprocess (python,linux)

I'm running two scripts in parallel as follows:

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

The above code is in a file called multi.py

Both 'tsn.py' and 'lsn.py' were logging data to separate text files using file.write(). If I run the .py files individually they log data just fine, however when I run multi.py the data to be logged prints on my screen just fine, but it doesn't get logged in the text files (i.e file.write() doesn't execute ). What is the issue and how do I work around that? Thanks.

EDIT: lsn.py looks like this. tsn.py is almost exactly the same

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

Upvotes: 0

Views: 68

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You need to close your files or let with do it for you:

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

Upvotes: 1

Related Questions