【发布时间】:2023-01-24 23:29:52
【问题描述】:
我正在编写一个小的实用函数,它接受 Python 文件位置的输入参数,以及一个在 Python 文件中调用的函数
例如src/path/to/file_a.py
def foo():
...
在效用函数中,我像这样解析参数:
python ./util.py --path src/path/to/file_a.py --function foo
foo函数需要稍后在另一个库的util.py中使用:
def compile():
compiler.compile(
function=foo,
etc
)
通过 argparse 导入 foo 函数的最佳方式是什么?
一些初步的想法:
util.py:
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--path", type=str)
parser.add_argument("--function", type=str)
return parser.parse_args()
def compile(path, function):
import path
compiler.compile(
function=path.function,
etc
)
if __name__ == "__main__":
args = get_args()
compile(
path=args.path
function=args.function
)
但是通过 argparse 导入,并将其添加到函数中似乎效果不佳。
还有使用sys.path.append的想法:
def compile(path, function):
import sys
sys.path.append(path)
但是我不确定如何从中导入 foo 函数。
【问题讨论】:
标签: python python-3.x argparse