Debug a python script with arguments from terminal

24,046

Solution 1

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

Solution 2

Try:

python -m pdb test.py arg1 arg2

Running python -m pdb runs pdb as a script. If test.py is somewhere in your path rather than your current working directory, this can be a helpful substitute:

python -m pdb "$(which test.py)" arg1 arg2
Share:
24,046
Kouichi C. Nakamura
Author by

Kouichi C. Nakamura

I'm a MATLAB user, learning signal processing and statistics for neuroscience. With poor background in maths and computer science, I'm a biologist struggling to understand the digital world!

Updated on October 11, 2020

Comments

  • Kouichi C. Nakamura
    Kouichi C. Nakamura over 3 years

    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?

  • Kouichi C. Nakamura
    Kouichi C. Nakamura about 9 years
    Now I found the description about this sytax in documentation which I've been reading many times!