python 脚本 envoke -h 或 --help 如果没有选择任何选项

标签 python python-2.7 optionparser

为了让我的脚本更加通用,所以我添加了一些标志。我的问题是,显然,只有在输入 -h 时帮助才有效。我想在未选择任何标志时调用 -h。

例如:

python 0_log_cleaner.py

Traceback (most recent call last):
      File "0_log_cleaner.py", line 51, in <module>
    getFiles(options.path,options.org_phrase,options.new_phrase,options.org_AN,options.new_AN,options.dst_path)
  File "0_log_cleaner.py", line 37, in getFiles
    for filename in os.listdir(path):
TypeError: coercing to Unicode: need string or buffer, NoneType found

但是如果我添加 -h 我得到:

python 0_log_cleaner.py -h

用法:示例:

python  0_log_cleaner.py --sp original_logs/ --dp clean_logs/ --od CNAME --nd New_CNAME --oan 10208 --nan NewAN

Options:
  -h, --help       show this help message and exit
  --sp=PATH        Path to the source logs ie original_logs/
  --dp=DST_PATH    Path to where sanitized logs will be written to ie
                   clean_logs
  --od=ORG_PHRASE  original domain name ie www.clientName.com, use the command
                   -od clientName
  --nd=NEW_PHRASE  domain name to replace -od. ie -od clientName -nd domain
                   makes all log that use to be www.clientName.com into
                   www.domain.com
  --oan=ORG_AN     original AN number
  --nan=NEW_AN     AN number to replace original. ie -oan 12345 -nan AAAA1
                   replaces all instances of the AN number 12345 with AAAA1

编辑 3 个答案 我要生成的代码示例 ^

import argparse
import sys

usage = "Description of function"
parser = argparse.ArgumentParser(description=usage)

parser.add_argument("--sp", dest="path", help='Path to the source logs ie logs/')
...
...(additional add arugments)

args = parser.parse_args()


def getFiles(path,org_phrase,new_phrase,org_AN,new_AN,dst_path):
    if not len(sys.argv) > 1:
        parser.print_help()
    else:
        run your logic

最佳答案

从这里借来的:Argparse: Check if any arguments have been passed

最终代码如下所示:

import argparse
import sys

usage = "Description of function"
parser = argparse.ArgumentParser(description=usage)

parser.add_argument("--sp", dest="path", help='Path to the source logs ie logs/')
...
...(additional add arugments)

args = parser.parse_args()


def getFiles(path,org_phrase,new_phrase,org_AN,new_AN,dst_path):
    if not len(sys.argv) > 1:
        parser.print_help()
    else:
        run your logic

关于python 脚本 envoke -h 或 --help 如果没有选择任何选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43287664/

相关文章:

python - 只能将 .dt 访问器与类似日期时间的值一起使用

ruby - 在 Ruby 中使用 OptionParse 强制强制命令行参数

python - python中skimage的rgb2gray : AttributeError: Nonetype object has no attribute ndim

python - 将输入从React.js/Electron应用传递到Python脚本?

Python __init__.py 和类

python-2.7 - 获取与列中最大值关联的行数据(Python/Pandas)

excel - 使用 Python 和 win32com 访问 Excel COM 中的枚举常量

boolean 选项的 Ruby OptionParser 短代码?

ruby - 如何在 ruby​​ 的 OptionParser 中使用变量参数

python - 为什么代码运行如此之慢以至于我在其中使用了 for 循环。有没有更快的方法?