我有一个运行几个子进程的python脚本。
我想要实现的是我想将子进程进程ID写入单独的日志文件。子进程可以运行几个小时,所以我想用PID跟踪它们。
不知怎的,我无法将PID写入日志文件,因为我遇到异常。
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")
这是我得到的输出,
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
虽然正在打印PID,但它没有写入文件。 注意:如果我只是通过替换“segmentprocess”将一些随机字符串写入日志文件,那么它确实有效。所以文件打开没有任何问题。
答案 0 :(得分:1)
您提供的堆栈跟踪似乎抛出了与代码中不同的异常。有没有我们没有看到的东西?你能提供你提供的行号范围吗?此外,如果您正在尝试调试异常,为什么要重新引发另一个异常?让真正的异常泡沫起来并在此处发布。不要抓住它,如果你这样做,请确保再次raise
。而不是
raise IOError("Error")
你应该
raise
或者根本不尝试/除外:
pidfile = open("pid.log", "a+")
try:
pidfile.write(segmentprocess)
finally:
pidfile.close()