【问题标题】:Python: How do I pass a big string as a single argument?Python:如何将大字符串作为单个参数传递?
【发布时间】:2011-05-17 13:26:24
【问题描述】:

我正在尝试将整个字符串作为参数传递给 python 脚本。我遇到的问题是 Python 假设我只想要字符串的第一个单词。

在下面的示例中,-l arg 代表日志,我希望它捕获整个字符串。

示例:

python myscript.py -l "Big String I want to as single argument"

代码如下:

try:
  opts, args = getopt.getopt(sys.argv[1:], 'hcrn:l:wo:a:emi', ["reset="])
  #-l is one of many arguments I'm looking for
except getopt.error, err:
  print str(err)
  sys.exit(2)

for o, a in getopts:
    if o in ("-l", "--log"):  #log
    logIt(a)  # Problem here a='Big'

如何获取第一个参数的整个字符串,而不仅仅是第一个单词?请举例。

【问题讨论】:

  • 为我工作。您使用的是什么操作系统或外壳?
  • 在循环中,getopts 是什么?

标签: python command-line-arguments


【解决方案1】:

首先:getopt 已经过时且不推荐使用。

请使用 Python 的 optparse 模块或更新的 argparse 模块(在 PyPI 上有一个用于 Python 2.X 的 argparse 的反向移植)。

第一个示例清楚地涵盖了使用 optparse 解决的用例:

http://docs.python.org/library/optparse.html

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")

(options, args) = parser.parse_args()

【讨论】:

  • 我的道歉,我没有看到它。我清楚地看到 OptionParser 如何接受单个单词的参数。但是,我找不到 OptionParser 接受“引号中的字符串”作为单个参数的任何示例。我错过了什么吗?
【解决方案2】:

只要你改正它,你的代码就可以完美运行。
问题可能出在您的logIt 函数中。 如果我更正此问题(它实际上不起作用在其发布的形式中):

for o, a in getopts:
    if o in ("-l", "--log"):  #log
    logIt(a)  # Problem here a='Big'

有了这个(并使用print):

for o, a in opts:
    if o in ("-l", "--log"):  #log
        print a  # No Problem here a=["Big String I want to as single argument"]

它打印应该打印的内容:

C:\Python26>python myscript.py -l "Big String I want to as single argument"
Big String I want to as single argument

所以可能你的问题不在于getopt,而在于你的logIt 函数。

【讨论】:

  • 奇怪...它在我的系统上的工作方式不同。如果我在 logIt 之前添加打印语句,则只打印“Big”。
  • @codingJoe 我在 cmd shell 中添加了我的输出。这是 windows XP 中的 python 2.6,最初的答案是在 win 7 上测试的。你使用的是什么操作系统?
  • 我在 win 7 上使用 python 2.6。全部由 cygwin 命令行驱动。回想起来,这个错误是相对较新的,同样的代码过去可以正常工作。但你是对的......它应该工作。我的临时解决方案是弹出一个easygui窗口并以这种方式捕获“Big Long String”。
【解决方案3】:

这应该是opts吗

try:
  opts, args = getopt.getopt(sys.argv[1:], 'hcrn:l:wo:a:emi', ["reset="])
  #-l is one of many arguments I'm looking for
except getopt.error, err:
  print str(err)
  sys.exit(2)

for o, a in opts:
    if o in ("-l", "--log"):  #log
    logIt(a)

【讨论】:

    猜你喜欢
    • 2016-07-21
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2022-12-09
    相关资源
    最近更新 更多