Pec*_*tum 12 python python-module python-2.7
这可能是一个愚蠢的问题,但我有一个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
Run Code Online (Sandbox Code Playgroud)
这是我要调用子脚本的父脚本; 它还使用arg解析器并执行其他一些逻辑
from configuration import parameterscript as paramscript
# Can I do something like this?
paramscript('parameters/test.params.json', test)
Run Code Online (Sandbox Code Playgroud)
在配置目录中,我还创建了一个空的init .py文件.
Ale*_*all 15
第一个参数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()
Run Code Online (Sandbox Code Playgroud)
其他地方:
from first_module import main
main(['-f', '/etc/hosts', '-t', 'json'])
Run Code Online (Sandbox Code Playgroud)
输出:
{'group': None, 'file': <_io.TextIOWrapper name='/etc/hosts' mode='r' encoding='UTF-8'>, 'type': 'json'}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2190 次 |
| 最近记录: |