簡體   English   中英

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的方法來做到這一點,但這里有一種使用子進程模塊的可能性:

例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM