我有 2 个文件,它们与子进程或 exec 一起runner.py
运行。
它们都有命令行选项。target.py
如果 runner 使用子进程运行目标,则可以:
$ python runner.py
run target.py with subprocess...
target.py: running with dummy = False
如果 runner 使用exec运行目标代码(带有-e
选项):
$ python runner.py -e
run target.py with exec...
usage: runner.py [-h] [-d]
runner.py: error: unrecognized arguments: -e
命令行参数-e
被target.py
代码“看到”(只接受一个--dummy
选项)并引发错误。
使用 exec 运行脚本时,如何将 args 隐藏到 argparse?
这是代码:
跑步者.py
import subprocess
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--exec", help="run with exec", action="store_true")
args = parser.parse_args()
target_filename = "target.py"
if args.exec:
print("run target.py with exec...")
source_code = open(target_filename).read()
compiled = compile(source_code, filename=target_filename, mode="exec")
exec(compiled) # OPTION 1 - error on argparse
# exec(compiled, {}) # OPTION 2 - target does not go inside "if main"
# exec(compiled, dict(__name__="__main__")) # OPTION 3 - same error as OPTION 1
else:
print("run target.py with subprocess...")
subprocess.run(["python3", target_filename])
我试图用上面注释的选项隐藏全局变量,但没有运气。
似乎与argparse的工作方式有关。
目标.py
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--dummy", help="a dummy option", action="store_true")
args = parser.parse_args()
print(f"target.py: running with dummy = {args.dummy}")