python调用一个使用argparser的模块
这可能是一个愚蠢的问题,但我有一个 python 脚本,当前使用 argparser 接收一堆争论,我想将此脚本作为另一个 python 脚本中的模块加载,这很好.但我不确定如何调用模块,因为没有定义函数;如果我只是从 cmd 调用它,我还能像我一样调用它吗?
This is probably a silly question, but I have a python script that current takes in a bunch of arguements using argparser and I would like to load this script as a module in another python script, which is fine. But I am not sure how to call the module as no function is defined; can I still call it the same way I do if I was just invoking it from cmd?
这是子脚本:
import argparse as ap
from subprocess import Popen, PIPE
parser = ap.ArgumentParser(
description='Gathers parameters.')
parser.add_argument('-f', metavar='--file', type=ap.FileType('r'), action='store', dest='file',
required=True, help='Path to json parameter file')
parser.add_argument('-t', metavar='--type', type=str, action='store', dest='type',
required=True, help='Type of parameter file.')
parser.add_argument('-g', metavar='--group', type=str, action='store', dest='group',
required=False, help='Group to apply parameters to')
# Gather the provided arguements as an array.
args = parser.parse_args()
... Do stuff in the script
这是我想从中调用子脚本的父脚本;它还使用 arg 解析器并执行一些其他逻辑
and here is the parent script that I want to invoke the child script from; it also uses arg parser and does some other logic
from configuration import parameterscript as paramscript
# Can I do something like this?
paramscript('parameters/test.params.json', test)
在配置目录中,我还创建了一个空的 init.py 文件.
Inside the configuration directory, I also created an init.py file that is empty.
parse_args
的第一个参数是一个参数列表.默认情况下它是 None
,这意味着使用 sys.argv
.所以你可以这样安排你的脚本:
The first argument to parse_args
is a list of arguments. By default it's None
which means use sys.argv
. So you can arrange your script like this:
import argparse as ap
def main(raw_args=None):
parser = ap.ArgumentParser(
description='Gathers parameters.')
parser.add_argument('-f', metavar='--file', type=ap.FileType('r'), action='store', dest='file',
required=True, help='Path to json parameter file')
parser.add_argument('-t', metavar='--type', type=str, action='store', dest='type',
required=True, help='Type of parameter file.')
parser.add_argument('-g', metavar='--group', type=str, action='store', dest='group',
required=False, help='Group to apply parameters to')
# Gather the provided arguements as an array.
args = parser.parse_args(raw_args)
print(vars(args))
# Run with command line arguments precisely when called directly
# (rather than when imported)
if __name__ == '__main__':
main()
然后在别处:
from first_module import main
main(['-f', '/etc/hosts', '-t', 'json'])
输出:
{'group': None, 'file': <_io.TextIOWrapper name='/etc/hosts' mode='r' encoding='UTF-8'>, 'type': 'json'}