如何从脚本中执行另一个python脚本并进行调试? [英] How to execute another python script from your script and be able to debug?

查看:141
本文介绍了如何从脚本中执行另一个python脚本并进行调试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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 不会到预期的结果,因为它不运行 __ main __

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

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

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

您对此问题有什么解决方案?

What solution do you see for this issue?

我正在寻找不需要您修改 another.py 脚本。可能这需要在执行之前先修改 sys.argv

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.

推荐答案

基于从EOL收到的建议,我对 execfile()进行了扩展,它确实解决了其局限性 execfile2()

Based on the recommendation received from EOL, I made an extension to execfile() that does solve its limitations execfile2()

下面是代码,但是更新的版本将在此处发布。它与 execfile()向后兼容。

Below is the code, but newer versions will be published here. It is backwards 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

这篇关于如何从脚本中执行另一个python脚本并进行调试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆