John Smith John Smith - 2 months ago 16
Python Question

Debug a python script with arguments from terminal

I have a python script that takes input arguments and runs in response to the following command in terminal (bash, Mac OSX).

python test.py arg1 arg2


Is there a good way to run the same script in debug mode without editing the code to include
import pdb
and
pdb.set_trace()
?

For example, if I'm using iPython console, I can do this by the following:

%run -d test.py arg1 arg2


This is pretty straightforward, isn't it? To achieve the same thing in terminal, I thought the following might work, but it did not:

python -c "import pdb; import sys; sys.argv = ['test.py', arg1, arg2];pdb.run('test.py')"


The code ran with the arguments, but not in
pdb
's debugging mode. Is it just hard to do and I should stick with
pdb.set_trace
or iPython's
%run -d
?

Answer

To debug a python script wit input arguments in Spyder IDE (2.3.4)

  1. Run > Configure...
  2. Select a run configuration > (Choose the script of interest that is open)
  3. General settings> Command line options: arg1 arg2 arg3 (use a space as delimiter just as in commandline)
  4. Working directory: (Choose the folder)
  5. Click OK

Then Debug from menu. This is equivalent to execute the following in iPython console in Spyder.

debugfile('/Users/xxx/xxx/test.py', args='arg1 arg2', wdir='/Users/xxx/xxx/')

Doing it with PyCharm is quite similar.

  1. Run > Edit Configurations
  2. Choose the python script from the menu
  3. The Configuration pane
  4. Script parameters: arg1 arg2

Then Run > Debug > Choose the file.

In iPyhton Console you can also try this (suppose test.py is in your current folder):

%run -d test.py arg1 arg2