Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute another python script from your script and be able to debug?

You have wrapper python script that is calling another python script, currently using os.system('python another.py some-params').

You want to be able to debug both scripts and if you use os.system() you'll loose the debugger, so it does make sense to load the second script using the same interpretor instead of starting another one.

import doesn't to the expected thing because it does not run the __main__.

Other variants, like exec() or runpy seams to miss the argv parameters.

What solution do you see for this issue?

I'm looking for a solution that does not require you to modify the another.py script. Probably this will require to modify the sys.argv before executing it.

like image 859
sorin Avatar asked Sep 07 '10 10:09

sorin


People also ask

How do I run and debug a Python script?

Starting Python Debugger To start debugging within the program just insert import pdb, pdb. set_trace() commands. Run your script normally and execution will stop where we have introduced a breakpoint. So basically we are hard coding a breakpoint on a line below where we call set_trace().

How do I debug a Python script from the command line?

Directly use command python pdg-debug.py without -m pdb to run the code. The program will automatically break at the position of pdb. set_trace() and enter the pdb debugging environment. You can use the command p variable to view the variables or use the command c to continue to run.


1 Answers

So far I found a solution that works only with Python 2.7+ (runpy.run_path() was introduced in Python 2.7).

If you can find one that works with 2.6 (or even 2.5) you are welcome to post it.

import runpy, sys
saved_argv = sys.argv
... # patch sys.argv[1:] and load new command line parameters
# run_path() does change only sys.argv[0] but restores it
runpy.run_path('another.py', run_name="__main__")
sys.argv = saved_argv # restore sys.argv
like image 167
sorin Avatar answered Oct 06 '22 07:10

sorin