How do you debug the code in the PyCharm IDE when it requires console input? 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; you could simply use step into as shown below. - Enable 'Run with console' under your run configuration first.
Change tab to console in your debugger.
Click on step into until you see the question in the console.
Input your answer as needed.
Click on continue or any other action from your debugger as needs be.
If you'd like to debug through running a script in CLI you're looking for something on the lines of pdb (Python Debugger). You can read more here.
Example:
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.
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. I provided the screenshots that illustrate the formula,
Now, switch from the debugger to the console and provide the desired input.
If you're using Pycharm 2018.3 or above you can redirect your input to a file.
PS. I haven't tried this but it should work fine.
Related
I'm just getting started with Python and trying to get some easy code-examples to compile. I am using the 'Spyder' Editor and everytime I run code it shows 'runfile(...)' before the actual compiled code in the console.
Is there a way to prevent this behaviour?
Try including this instead immediately prior to your code. The terminal will now return a clean code only response:
cls = lambda: print("\033[2J\033[;H", end='')
cls()
you are trying to run the code, instead go to settings, keyboard shortcuts, and look for "run selection" it will have a shortcut assigned to it
Now select all the code and use the shortcut
it will only give you in and out
I am new to python and pycharm.
I am writing a program that takes years to run, so I want to see the iteration number while debugging.
this is my code:
import urllib2
for i in range(n):
print i
responses[i]=u2.urlopen(urls[i])
(I have an array of n urls)
so, when I run it I see the outputs:
0
1
2
3
etc
but when I am debugging I don't see the output.
any idea anyone?
Its a simple code block and there should not be any problem with Pycharm debugger. I suggest to use latest PyCharm version 5.0.
Right click on your python file and select 'Debug yourPythonFile.py'.It should print value of i.
Just a small suggestion, use (responses.append(u2.urlopen(urls[i])) instead of responses[i]=u2.urlopen(urls[i])
so i am making a class of employess, and i want to make a function that returns total time worked
try
1, running this through spyder
2. running it in console
gives different results :S
class Employee(object):
def __init__(self, wage, wage1, hours_accounting=[]):
self.wage=wage
self.wage1=wage1
self.hours_accounting=hours_accounting
def work(self):
A=H,M=input('when did you start work today? format hh,mm')
B=H1,M1=input('when did you stop work today? format hh,mm')
total_time_in_hours=H1-H + (M1-M)/60
return total_time_in_hours
amanda=Employee(100, 50)
amanda.work()
07,15
21,00
#
why?? thanks in advance!
(Spyder dev here) Before Spyder 2.3.0 we ran this code while starting a console:
from __future__ import division
which makes things like 2/3 to return 0.6666 instead of 0 (which is the normal behavior in Python 2).
To change this you have three options:
Update to 2.3.0
If you are using a Python Console, you need to go to
Preferences > Console > Advanced Settings > PYTHONSTARTUP replacement
and select the option called
Default PYTHONSTARTUP script.
If you are using the IPython console, you need to go to
Preferences > IPython Console > Graphics
and deselect the option called
Automatically load Pylab and NumPy modules
Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?
I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.
I frequently use this:
def interact():
import code
code.InteractiveConsole(locals=globals()).interact()
You could try using the interactive option for python:
python -i program.py
This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.
Here's how you should do it (IPython > v0.11):
import IPython
IPython.embed()
For IPython <= v0.11:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # this call anywhere in your program will start IPython
You should use IPython, the Cadillac of Python REPLs. See http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython
From the documentation:
It can also be useful in scientific
computing situations where it is
common to need to do some automatic,
computationally intensive part and
then stop to look at data, plots, etc.
Opening an IPython instance will give
you full access to your data and
functions, and you can resume program
execution once you are done with the
interactive part (perhaps to stop
again later, as many times as needed).
You can launch the debugger:
import pdb;pdb.set_trace()
Not sure what you want the REPL for, but the debugger is very similar.
To get use of iPython and functionality of debugger you should use ipdb,
You can use it in the same way as pdb, with the addition of :
import ipdb
ipdb.set_trace()
I just did this in one of my own scripts (it runs inside an automation framework that is a huge PITA to instrument):
x = 0 # exit loop counter
while x == 0:
user_input = raw_input("Please enter a command, or press q to quit: ")
if user_input[0] == "q":
x = 1
else:
try:
print eval(user_input)
except:
print "I can't do that, Dave."
continue
Just place this wherever you want a breakpoint, and you can check the state using the same syntax as the python interpreter (although it doesn't seem to let you do module imports).
It's not very elegant, but it doesn't require any other setup.
Great answers above, but if you would like this functionality in your IDE. Using Visual Studio Code (v1.5.*) with Python Setup:
Highlight the lines you would like to run and
right click and select Run Selection/Line in Interactive Window from the drop down.
Press shift + enter on your keyboard.
Right click on the Python file you want to execute in the file explorer and select Run Current File in Interactive Window
This will launch an interactive session, with linting, code completion and syntax highlighting:
Enter the code you would like to evaluate, and hit shift + enter on your keyboard to execute.
Enjoy Python!
Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?
I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.
I frequently use this:
def interact():
import code
code.InteractiveConsole(locals=globals()).interact()
You could try using the interactive option for python:
python -i program.py
This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.
Here's how you should do it (IPython > v0.11):
import IPython
IPython.embed()
For IPython <= v0.11:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # this call anywhere in your program will start IPython
You should use IPython, the Cadillac of Python REPLs. See http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython
From the documentation:
It can also be useful in scientific
computing situations where it is
common to need to do some automatic,
computationally intensive part and
then stop to look at data, plots, etc.
Opening an IPython instance will give
you full access to your data and
functions, and you can resume program
execution once you are done with the
interactive part (perhaps to stop
again later, as many times as needed).
You can launch the debugger:
import pdb;pdb.set_trace()
Not sure what you want the REPL for, but the debugger is very similar.
To get use of iPython and functionality of debugger you should use ipdb,
You can use it in the same way as pdb, with the addition of :
import ipdb
ipdb.set_trace()
I just did this in one of my own scripts (it runs inside an automation framework that is a huge PITA to instrument):
x = 0 # exit loop counter
while x == 0:
user_input = raw_input("Please enter a command, or press q to quit: ")
if user_input[0] == "q":
x = 1
else:
try:
print eval(user_input)
except:
print "I can't do that, Dave."
continue
Just place this wherever you want a breakpoint, and you can check the state using the same syntax as the python interpreter (although it doesn't seem to let you do module imports).
It's not very elegant, but it doesn't require any other setup.
Great answers above, but if you would like this functionality in your IDE. Using Visual Studio Code (v1.5.*) with Python Setup:
Highlight the lines you would like to run and
right click and select Run Selection/Line in Interactive Window from the drop down.
Press shift + enter on your keyboard.
Right click on the Python file you want to execute in the file explorer and select Run Current File in Interactive Window
This will launch an interactive session, with linting, code completion and syntax highlighting:
Enter the code you would like to evaluate, and hit shift + enter on your keyboard to execute.
Enjoy Python!