【问题标题】:How to handle quotes in python argument如何处理python参数中的引号
【发布时间】:2017-04-18 19:17:33
【问题描述】:

我在 python3.5 中使用Argparse。我需要的参数之一是一个长字符串,它可以包含任何字符,如单引号或双引号。我不想限制用户如何使用这个 python 脚本并强迫他删除这个字符。所以我正在寻找一种解决方案来处理我的代码中的引号。

这是我的参数解析器:

class MyParser(argparse.ArgumentParser):
    def error(self, message):
        sys.stderr.write('Error: %s\n' % message)
        self.print_help()
        sys.exit(2)

    def msg(name=None):
        return '''python3.5 file.py Text'''

parser = MyParser(description='You must pass exactly one arguments after classifier.py . Use quotes after and before the argument.', usage=MyParser.msg())
parser.add_argument('text', help='"News Text" for classification (Required Parameter)')
args = parser.parse_args()

这种类型的参数失败并出现无法识别的错误:

>>> python3.5 file.py "Apps infected by Gooligan include "Perfect Cleaner," and more."
Error: unrecognized arguments: Cleaner, and more.

而且有时没有任何错误:

>>> python3.5 file.py "Now "Support is expensive, and, when you're Google or any other vendor," said Michael Jude."
>

我想知道第二类错误的原因以及在我的代码中处理错误的解决方案,而无需注意参数。

【问题讨论】:

    标签: python parameter-passing python-3.5 argparse


    【解决方案1】:

    这不是argparse 问题。这是shell如何拆分输入行并将其传递给Python的问题。查看 sys.argv 以了解 argparse 必须使用的内容。

    我相信反斜杠允许您在字符串中包含引号和其他特殊字符 - 但要进行实验。

    从侧边栏: Python argparse argument with quotes

    【讨论】:

    • 你也可以在整个论点周围尝试单引号。
    • @kindall 但要注意单引号字符串中的单引号不能转义。
    【解决方案2】:

    与许多人认为的不同,不是 shell 将命令行拆分为参数。它也不是进程加载器,尽管它自己进行一些解析和解释。

    命令行由python进程本身解析为参数向量。根据 python 的构建方式,这将是某种运行时库。对于 Windows 构建,这很可能是 MS Visual C++ 运行时库。有关它如何解析命令行的更多详细信息,请参阅 Visual C++ 文档:Parsing C++ command-Line arguments

    要查看未处理的命令行,可以使用以下代码:

    import win32api
    print(win32api.GetCommandLine())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2019-04-15
      • 1970-01-01
      相关资源
      最近更新 更多