根据从 EOL 收到的建议,我做了一个扩展execfile()
,确实解决了它的限制execfile2()
下面是代码,但更新的版本会在这里发布。它向后兼容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