我正在使用 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)
关于python - 如何使用 argparse 获得不带连字符 (--) 的可能参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56255987/