avizzzy
avizzzy

Reputation: 535

Error thrown when writing subprocess pid to a log file

I have a python script that runs a couple of subprocesses.

What I am trying to achieve is that i'd like to write the subprocess process IDs to a separate log file. The subprocess can run for even few hours, so I'd like to keep track of them with the PIDs.

Somehow I am unable to write the PIDs to a log file, as I bump into exceptions.

tmprocess = subprocess.Popen(['sudo', logstashbin, '-f', tmconf], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
tmprocess.wait()
segmentprocess = subprocess.Popen(['sudo', logstashbin, '-f', segmentconf], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).pid
print segmentprocess

try:
    pidfile = open("pid.log", "a+")
    try:
        pidfile.write(segmentprocess)
    finally:
        pidfile.close()
except:
    raise IOError("Error")

This is the output I get,

1237
Traceback (most recent call last):
  File "./init.py", line 285, in <module>
    main(sys.argv[1:])
  File "./init.py", line 282, in main
    init(arg)
  File "./init.py", line 264, in init
    run_logstash(langPath)
  File "./init.py", line 228, in run_logstash
    raise IOError("Error")
IOError: Error

Although the PID is being printed, it is not getting written to the file. Note: If I just write some random string to the log file by replacing "segmentprocess", then it does work. So there is nothing wrong with file open.

Upvotes: 1

Views: 290

Answers (1)

Jamie Counsell
Jamie Counsell

Reputation: 8143

The stack trace you provided appears to throw a different exception than is in your code. Is there something we're not seeing? Can you include the line number range that you have provided? Also, if you're trying to debug the exception, why re-raise a different exception? Just let the real exception bubble up and post it here. Do not catch it, and if you do, make sure you just raise again. Instead of

raise IOError("Error")

You should just

raise

Or not try/except at all:

pidfile = open("pid.log", "a+")
try:
    pidfile.write(segmentprocess)
finally:
    pidfile.close()

Upvotes: 1

Related Questions