python 调用一个使用 argparser 的模块

python calling a module that uses argparser

这可能是个愚蠢的问题,但我有一个 python 脚本,当前使用 argparser 进行了一系列争论,我想将此脚本作为模块加载到另一个 python脚本,这很好。但是我不确定如何调用模块,因为没有定义函数;如果我只是从 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 解析器并执行一些其他逻辑

from configuration import parameterscript as paramscript

# Can I do something like this?
paramscript('parameters/test.params.json', test)

在配置目录中,我还创建了一个空的init.py文件。

parse_args 的第一个参数是一个参数列表。默认情况下它是 None,这意味着使用 sys.argv。所以你可以这样安排你的脚本:

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'}

可能有一种更简单、更 pythonic 的方法来做到这一点,但这里有一种可能使用 subprocess 模块:

示例:

child_script.py

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", help="your name")
args = parser.parse_args()

print("hello there {}").format(args.name)

然后另一个 Python 脚本可以像这样调用该脚本:

calling_script.py:

import subprocess

# using Popen may suit better here depending on how you want to deal
# with the output of the child_script.
subprocess.call(["python", "child_script.py", "-n", "Donny"])

执行上面的脚本会得到以下输出:

"hello there Donny"

一种选择是将其称为子流程调用,如下所示:

import subprocess
childproc = subprocess.Popen('python childscript.py -file yourjsonfile')
op, oe = childproc.communicate()
print op