如何在 Pycharm 中使用 Popen 调试代码运行 [英] How to debug code run using Popen in Pycharm

查看:78
本文介绍了如何在 Pycharm 中使用 Popen 调试代码运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个从其他人那里继承的代码库,该代码库广泛使用了用户输入.出于这个原因,我使用 subprocess.Popen 运行它.这是一个例子.以下脚本 (caller.py) 调用第三方代码.

I am running a codebase I have inherited from someone else which makes extensive use of user input. For this reason I am running it using subprocess.Popen. Here is an example. The following script (caller.py) calls the third-party code.

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) 通过接受来自用户的几个输入参数来模拟我提供的源代码的行为:

The following script (example.py) emulates behavior of the source code I was provided, by accepting a couple of input arguments from the user:

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))

运行代码工作正常,我得到了预期的输出.

Running the code works fine, and I get the expected output.

调试代码部分有效,但部分无效.调试器成功地附加到子进程 p 以便放置在 example.py 中的任何断点都可以工作.然而,调试控制台似乎没有成功附加到子进程.当我尝试在调试控制台中输入一些变量时,它们不会打印出来,即使它们在我的调试会话中显示为活动变量.

Debugging the code partially works, but partially doesn't. The debugger successfully attaches to the child process p such that any breakpoints placed in example.py will work. However it seems that the debug console does not successfully attached to the child process. When I try to enter some variables in the debug console, they do not print out, even if they appear as active variables in my debug session.

编辑

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

It turns out this might be a bug. I have asked the same question in pycharm's official forum and they made an issue out of it:

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

所以我想我要寻找的是一种有效的解决方法,它允许我将常规的 Python 解释器与调试器结合使用来检查和运行变量操作.

So I guess what I'd be looking for is an effective workaround which would allow me to use a regular python interpreter in combination with the debugger to inspect and run operations on variables.

推荐答案

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

I have had a similar issue with python and docker logs. What solved was running python with the -u flag as described here. Perhaps try changing your Popen call to use python and then include the -u flag. e.g. Popen(["python", "-u", "example2.py"], stdout=PIPE, stdin=PIPE, stderr=STDOUT, encoding='utf-8')

这篇关于如何在 Pycharm 中使用 Popen 调试代码运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆