Python optparse 和参数中的空格

发布于 2024-09-25 16:51:47 字数 617 浏览 2 评论 0原文

使用 optparse 时,我想获取选项后的整个字符串,但我只获取第一个空格之前的部分字符串。

例如:

python myprog.py --executable python someOtherProg.py

我在“可执行文件”中得到的只是“python”。

是否可以使用 optparse 解析此类行,还是必须使用 argparse 来执行此操作?

€:我已经尝试将其括在“s”中。但是在深入研究代码后,我发现子进程调用无法处理参数。

带有命令行的字符串被塞进列表“args”中。

args = [self.getExecutable()] + self.getArgs().split()

就像

"[python D:\\\workspace\\\myprog\\\src\\\myprog.py]"

这样当我使用它时,会出现系统找不到文件异常。

args[0]

但是

,如果子进程模块一开始没有获取字符串,则它会从列表中构建一个命令行 。目前不解释这种行为。

When using optparse i want to get the whole string after an option, but I only get part of it up to the first space.

e.g.:

python myprog.py --executable python someOtherProg.py

What I get in 'executable' is just 'python'.

Is it possible to parse such lines using optparse or do you have to use argparse to do it?

€: I have already tried enclosing it in "s. But after digging further into the code I found out that the subprocess invocation can't handle the argument.

The string with the commandline gets crammed into a list 'args'.

args = [self.getExecutable()] + self.getArgs().split()

It's like

"[python D:\\\workspace\\\myprog\\\src\\\myprog.py]"

That gives me the System can't find file exception. When I use

args[0]

it works. But I loose the arguments to the executable.

The subprocess module builds a cmdline from a list if it does not get a string in the first place, so I can't explain that behavior at the moment.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不打扰别人 2024-10-02 16:51:47

您可以将它们括在引号中,以使它们能够与现有代码一起使用。

python myprog.py --executable "python someOtherProg.py"

是否可以使用 optparse 解析此类行,还是必须使用 argparse 来执行此操作?

我不知道是否/如何使用 optparse 来做到这一点,因为我还没有真正使用过 optparse

不过,我可以通过 argparse 帮助您。这是一个简单的示例:

#!/usr/bin/python
import argparse, sys

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Demonstration of Argparse.')
    parser.add_argument('-e', '--executable', nargs = '+', help = 'List of executables')
    args = parser.parse_args(sys.argv[1:])
    print args.executable

用法:

manoj@maruti:~$ python myprog.py --executable python someOtherProg.py
['python', 'someOtherProg.py']

我还建议从 optparse 切换到 argparseOptparse 自 2.7 起已弃用

You can enclose them in quotes to make them work with the existing code.

python myprog.py --executable "python someOtherProg.py"

Is it possible to parse such lines using optparse or do you have to use argparse to do it?

I don't know if/how you can do it with optparse as I haven't really worked with optparse.

I can however help you out with argparse. Here is a quick example:

#!/usr/bin/python
import argparse, sys

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = 'Demonstration of Argparse.')
    parser.add_argument('-e', '--executable', nargs = '+', help = 'List of executables')
    args = parser.parse_args(sys.argv[1:])
    print args.executable

And usage:

manoj@maruti:~$ python myprog.py --executable python someOtherProg.py
['python', 'someOtherProg.py']

I'd also recommend switching from optparse to argparse. Optparse is deprecated since 2.7.

尴尬癌患者 2024-10-02 16:51:47

我找到了另一个很好的替代方案 shlex - 用于简单的类似 shell 语法的词法分析器类。

源链接:如何解析命令行正则表达式?

>>> import shlex
>>> shlex.split('"param 1" param2 "param 3"')
['param 1', 'param2', 'param 3']
>>> shlex.split('"param 1" param2 "param 3"')
Traceback (most recent call last):
    [...]
ValueError: No closing quotation
>>> shlex.split('"param 1" param2 "param 3\\""')
['param 1', 'param2', 'param 3"']

I've found another good alternative shlex - A lexical analyzer class for simple shell-like syntaxes.

Source link: How to parse a command line with regular expressions?

>>> import shlex
>>> shlex.split('"param 1" param2 "param 3"')
['param 1', 'param2', 'param 3']
>>> shlex.split('"param 1" param2 "param 3"')
Traceback (most recent call last):
    [...]
ValueError: No closing quotation
>>> shlex.split('"param 1" param2 "param 3\\""')
['param 1', 'param2', 'param 3"']
债姬 2024-10-02 16:51:47

您看到的行为来自于这样一个事实:解析命令行并将其分离为 sys.argv 的单词的是您的 shell,而不是 python。 Python 由 shell 通过 exec() 启动,argv 已填充。

大多数 shell 都会在空格处分割 argv 项,除非您通过引用或转义告诉它们不要这样做。

报价的工作原理如上所述。

在许多 shell 中,您可以这样做:

python myprog.py --executable python\ someOtherProg.py

反斜杠转义后面的空格,而不需要引号。

The behavior you see comes from the fact that it's your shell, not python, that parses the command line and separates it into the words of sys.argv. Python is launched by the shell via exec() with argv already populated.

Most shells will split argv items at spaces unless you tell them not to by quoting or escaping.

Quotes work as described above.

In many shells you could do this:

python myprog.py --executable python\ someOtherProg.py

The backslash escapes the following space without requiring quotes.

离笑几人歌 2024-10-02 16:51:47

如果您知道参数标志后将获得多少个单词,则可以修改在 optparse 中创建 --executable 选项的方式来正确处理这种情况:

您可以将 optparse 解析器设置为查找两个(或更多)单词,而不是在选项标志后采用单个单词:

from optparse import OptionParser
parser = OptionParser()

parser.add_option("-f", "--file", action="store", dest="filename",
                       help="File to be processed.", metavar="FILE")
parser.add_option("-e", "--executable", action="store", dest="my_exe",
                       help="Command to be executed", metavar="EXE",
                       nargs=2)

在此代码片段,-f--file 选项仅需要单个单词并将其作为字符串(默认)存储在 filename 变量中。

相比之下,由于 nargs=2 选项,-e--executable 选项需要两个单词。这将导致 -e--executable 标志后面找到的两个单词作为字符串存储在 Python 列表 my_exe 中。

查看:http://docs.python.org/library/optparse.html有关 optparse 的更多信息,请记住,从 2.7 开始,它已被弃用,取而代之的是 argparse

If you know how many words after the argument flag you are going to get, you can modify the way you create the --executable option in in optparse to properly handle the situation:

Instead of taking a single word after the option flag you can set the optparse parser to look for two (or more) words:

from optparse import OptionParser
parser = OptionParser()

parser.add_option("-f", "--file", action="store", dest="filename",
                       help="File to be processed.", metavar="FILE")
parser.add_option("-e", "--executable", action="store", dest="my_exe",
                       help="Command to be executed", metavar="EXE",
                       nargs=2)

In this snippet, the -f or --file option only expects a single word and stores it as a string (the default) in the filename variable.

In contrast the -e, --executable option expects two words because of the nargs=2 option. This will result in the two words found behind the -e or --executable flag to be stored as strings in a Python list my_exe.

Check out: http://docs.python.org/library/optparse.html for more info on optparse, and remember it has been deprecated as of 2.7 in favour of argparse.

去了角落 2024-10-02 16:51:47

如果您无法升级到 argparse,只是为了最终确定此答案列表。

Optparse 无法处理这些情况(多个字符串)。您只能使用 nargs 来指定特定数量的变量,但没有什么比“一个或多个”更好的了。您需要破解它或使用不同的库(例如argparse或其他)。

Just to finalize this answer list if you cannot upgrade to argparse.

Optparse is not able to handle these situations (multiple strings). You can only use nargs to specify particular amount of valiables, but there is nothing like "one or more". You need to hack it or use different library (e.g. argparse or other).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文