python调用一个使用argparser的模块 [英] python calling a module that uses argparser

查看:40
本文介绍了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'}

这篇关于python调用一个使用argparser的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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