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

You have a python script shell that calls another python script, currently uses os.system('python another.py some-params') .

You want to be able to debug both scripts, and if you use os.system() , you lose the debugger, so it makes sense to load the second script using the same interpreter, rather than running the other.

import not as expected because it does not start __main__ .

Other options, such as exec() or runpy , skip the argv options.

What solution do you see on this issue?

I am looking for a solution that does not require changing another.py script. You probably need to modify sys.argv to do this.

+4
source share
4 answers

Based on a recommendation from EOL, I made an extension to execfile() , which removes its limitations of execfile2 ()

Below is the code, but newer versions will be published here . It is backward compatible with execfile() .

 def execfile2(filename, _globals=dict(), _locals=dict(), cmd=None, quiet=False): _globals['__name__']='__main__' saved_argv = sys.argv # we save sys.argv if cmd: sys.argv=list([filename]) if isinstance(cmd , list): sys.argv.append(cmd) else: sys.argv.extend(shlex.split(cmd)) exit_code = 0 try: execfile(filename, _globals, _locals) except SystemExit as e: if isinstance(e.code , int): exit_code = e.code # this could be 0 if you do sys.exit(0) else: exit_code = 1 except Exception: if not quiet: import traceback traceback.print_exc(file=sys.stderr) exit_code = 1 finally: if cmd: sys.argv = saved_argv # we restore sys.argv return exit_code 
+2
source

So far, I have found a solution that only works 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 can 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 
+6
source

Do you have control over another.py ? It would be nice to change it and add the main() method. main() can be called if __name__ == '__main__' . This will greatly alleviate your problems. This is also unit testing.

+2
source

You can make the call to the main unit a function. This way you can call the same function when importing as a module.

 def main(): print "All start up commands" if __name__ == "__main__": main() 
+1
source

All Articles