![](/img/trans.png)
[英]is it possible to denote some set of argparse's arguments without using subparsers?
[英]How to have a list of possible arguments without hyphens(--) using argparse
我正在使用Python3构建客户端。 我需要解析用户发送的参数。 说我有一个带有以下代码的python脚本client.py
def upload_file(path,compress=False):
print(path)
print("uploading")
def download_file(name):
print(name)
print("downloading")
如果使用参数'upload_file'调用脚本,则应调用upload_file
函数,依此类推...
以下是调用脚本的各种可能方式。
python client.py upload_file -path /home/user/sample.gz
python client.py upload_file -path /home/user/sample_folder --compress=True
python client download_file -name sample.gz
我如何使用argparse
创建一个解析器,该解析器调用适当的函数并在传递无效参数时引发适当的错误消息?
这是一个如何在示例中使用解析器的示例:
import os
import argparse
def upload_file(path,compress=False):
print(path)
print("uploading")
def download_file(name):
print(name)
print("downloading")
def main(argv):
action = argv.action_to_take
file = argv.file
if action == 'download':
download_file(file)
elif action == 'upload':
upload_file(file)
else:
print('Action not recognised')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Action to take')
parser.add_argument('action_to_take', help='input file path on HDFS')
parser.add_argument('file', help='file to download or upload')
args = parser.parse_args()
main(args)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.