如何从脚本执行另一个python脚本并能够调试?

sor*_*rin 8 python debugging command-line runpy

你有一个调用另一个python脚本的包装python脚本,目前正在使用os.system('python another.py some-params').

您希望能够调试这两个脚本,如果您使用,os.system()您将松开调试器,因此使用相同的解释器加载第二个脚本而不是启动另一个脚本是有意义的.

import没有达到预期的目的,因为它没有运行__main__.

其他变体,例如exec()runpy接缝错过argv参数.

你对这个问题有什么解决方案?

我正在寻找一个不需要你修改another.py脚本的解决方案.可能这需要sys.argv在执行之前修改它.

sor*_*rin 7

到目前为止,我发现了一个仅适用于Python 2.7+的解决方案(在Python 2.7中引入了runpy.run_path()).

如果您能找到一个适用于2.6(甚至2.5)的产品,欢迎您发布.

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
Run Code Online (Sandbox Code Playgroud)


sor*_*rin 2

根据 EOL 收到的建议,我进行了扩展,确实解决了execfile2()execfile()的局限性

下面是代码,但更新的版本将在此处发布。它向后兼容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
Run Code Online (Sandbox Code Playgroud)