无法使用子进程调试python脚本

时间:2015-03-16 05:19:55

标签: python python-2.7 python-3.x

我编写了一个python函数,它使用PSTools(psexec)在远程桌面上运行另一个python脚本。当函数只调用一次时,我已成功运行了几次脚本。但是当我从另一个文件多次调用该函数时,子进程不会在第二次调用中运行。事实上,它会在第二次迭代中立即退出整个程序,而不会抛出任何异常或Traceback。

    controlpc_clean_command = self.psexecpath + ' -s -i 2 -d -u ' + self.controlPClogin + ' -p ' + self.controlPCpwd + ' \\' + self.controlPCIPaddr + ' cmd.exe /k ' + self.controlPC_clean_code

    logfilePath = self.psexeclogs + 'Ctrl_Clean_Log.txt'
    logfile = file(logfilePath,'w')

    try:

     process = subprocess.Popen(controlpc_clean_command, stdout = subprocess.PIPE,stderr = subprocess.PIPE)


     for line in process.stderr:
      print "** INSIDE SUBPROCESS STDERR TO START PSEXEC **\n"
      sys.stderr.write(line)
      logfile.write(line)


     process.wait()

    except OSError:
      print "********COULD NOT FIND PSEXEC.EXE, PLEASE REINSTALL AND SET THE PATH VARIABLE PROPERLY********\n"

以上代码完美运行一次。即使我从具有不同参数的不同python文件运行它,它运行良好。当我从一个文件中多次调用该函数时会出现问题,然后在第二次调用中,函数在打印“** INSIDE SUBPROCESS STDERR TO START PSEXEC ** \ n”之后退出,它甚至不会在主程序中打印任何内容之后。

我无法弄清楚如何调试此问题。因为我完全不知道该程序在打印此行后的位置。我该如何调试呢?

修改 在做了一些搜索后,我补充道     stdout,stderr = subprocess.communicate()

在我的脚本中的subprocess.Popen行之后。现在,我可以继续使用代码,但有一个问题。添加subprocess.communicate()后,现在没有任何内容写入日志文件'Ctrl_Clean_Log.txt'!如何在文件中写入以及继续执行代码?

1 个答案:

答案 0 :(得分:1)

也许你的第一个进程陷入等待并阻止其他进程。

https://docs.python.org/2/library/subprocess.html

Popen.wait()
    Wait for child process to terminate. Set and return returncode attribute.

Warning This will deadlock when using stdout=PIPE and/or stderr=PIPE and the 
child process generates enough output to a pipe such that it blocks waiting 
for the OS pipe buffer to accept more data. Use communicate() to avoid that.