将子过程PID写入日志文件时会丢弃错误



我有一个python脚本,该脚本运行了几个子过程。

我要实现的是,我想将子过程进程ID写入单独的日志文件。子过程甚至可以运行几个小时,所以我想用pids跟踪它们。

以某种方式我无法将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"来将一些随机字符串写入日志文件,那么它确实有效。因此,文件打开没有错。

您提供的堆栈跟踪似乎与代码中的不同例外相比。我们没有看到什么吗?您可以包括您提供的行号范围吗?另外,如果您想调试异常,为什么还要重新调整不同的异常?只要让真正的异常泡泡并将其发布在此处。不要抓住它,如果您这样做,请确保您再次再次raise。而不是

raise IOError("Error")

您应该只是

raise

或不尝试/除外:

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

相关内容

最新更新