简体   繁体   English

调试需要控制台输入的Python代码

[英]Debug Python code that requires console input

How do you debug the code in the PyCharm IDE when it requires console input? 当需要控制台输入时,如何在PyCharm IDE中调试代码? For example, I have a piece of code, 例如,我有一段代码,

        # if the config  already exists prompt what to do
        if pc and not self.prompt.ask_yesno('project_ovverride'):
            self.prompt.say('setup_abort')
            return

在此处输入图片说明

This breaks in the line highlighted and I wasn't able to proceed for not being able to provide the console input. 这在突出显示的行中中断了,并且由于无法提供控制台输入而无法继续。 At the moment, I comment it out, but, there might be a way to provide the required console input as well. 目前,我已将其注释掉,但是,也许也可以提供所需的控制台输入。

Thank you. 谢谢。

If you're simply looking to input via CLI while debugging; 如果您只是在调试时希望通过CLI输入; you could simply use step into as shown below. 您可以简单地使用step into ,如下所示。 - Enable 'Run with console' under your run configuration first. -首先在运行配置下启用“使用控制台运行”。

  1. Change tab to console in your debugger. 更改选项卡以在调试器中进行console
  2. Click on step into until you see the question in the console. 单击step into直到您在控制台中看到问题。
  3. Input your answer as needed. 根据需要输入答案。
  4. Click on continue or any other action from your debugger as needs be. 根据需要单击continue或调试器中的任何其他操作。

If you'd like to debug through running a script in CLI you're looking for something on the lines of pdb (Python Debugger). 如果您想通过在CLI运行脚本进行调试,那么您会在pdb (Python调试器)的行中pdb某些内容。 You can read more here . 您可以在这里阅读更多内容。

Example: 例:

my_example.py my_example.py

try:
    pdb_test = 1 / 0
except ZeroDivisionError:
    print('Argh stop it!')

Command Line: 命令行:

(venv) $ python3 -m pdb my_example.py
> /my_example.py(1)<module>()
-> try:
(Pdb) s
> /my_example.py(2)<module>()
-> a = 1 / 0
(Pdb) s
ZeroDivisionError: division by zero
> /my_example.py(2)<module>()
-> a = 1 / 0
(Pdb) 

What the above is showing is merely me using s to command the pdb to step - in the documentation you can find all the commands you might want to use including continue et cetera. 上面显示的只是我使用s命令pdb step -在文档中,您可以找到所有可能要使用的命令,包括continue等。

If you're using Pycharm 2018.3 or above you can redirect your input to a file. 如果您使用的是Pycharm 2018.3或更高版本,则可以将输入重定向到文件中。 PS. PS。 I haven't tried this but it should work fine. 我没有尝试过,但是应该可以正常工作。 在此处设置输入文件

Initially, we need to set the Run with Python console in the Run configuration of the PyCharm IDE and then, we can change the debugger window to the console window at the time of debugging the software. 最初,我们需要在PyCharm IDE的“运行”配置中设置Run with Python console ,然后在调试软件时将调试器窗口更改为控制台窗口。 I provided the screenshots that illustrate the formula, 我提供了说明公式的屏幕截图,

在此处输入图片说明

Now, switch from the debugger to the console and provide the desired input. 现在,从调试器切换到控制台,并提供所需的输入。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM