如何调试在Pycharm中使用Popen运行的代码

问题描述

我正在运行我从别人那里继承来的代码库,该代码库大量使用了用户输入。因此,我使用subprocess.Popen运行它。这是一个例子。以下脚本(caller.py调用第三方代码

from subprocess import Popen,PIPE,STDOUT
import sys
user_input = ['John','555']

communicate_argument = '\n'.join(user_input)
p = Popen([sys.executable,'example2.py'],stdout=PIPE,stdin=PIPE,stderr=STDOUT,encoding='utf-8')

stdout,stderr = p.communicate(communicate_argument)

print(stdout)

以下脚本(example.py)通过接受用户的几个输入参数来模拟所提供的源代码的行为:

name = input('What is your name\n')
age = input('What is your age\n')

print('You are {},and you are {} years old'.format(name,age))

运行代码可以正常工作,并且我得到了预期的输出

调试代码部分有效,但部分无效。调试器已成功附加到子进程p,以便放置在example.py中的所有断点都可以使用。但是,似乎调试 console 并未成功附加到子进程。当我尝试在调试控制台中输入一些变量时,即使它们在我的调试会话中显示为活动变量,也不会打印出来。

编辑

事实证明这可能是错误。我在pycharm的官方论坛上问了同样的问题,他们从中提出了一个问题:

https://intellij-support.jetbrains.com/hc/en-us/community/posts/360009571680-Debugging-code-run-through-subprocess-Popen

所以我想我想寻找的是一个有效的解决方法,它可以让我结合使用常规的python解释器和调试器来检查和运行变量操作。

解决方法

我在python和docker日志中也遇到了类似的问题。解决的方法是使用here中所述的-u标志运行python。也许尝试将您的Popen调用更改为使用python,然后包含-u标志。例如Popen(["python","-u","example2.py"],stdout=PIPE,stdin=PIPE,stderr=STDOUT,encoding='utf-8')