【问题标题】:Quoted string as optional argument to Python script引用的字符串作为 Python 脚本的可选参数
【发布时间】:2013-12-10 21:29:18
【问题描述】:

我有一个简单的实用程序脚本,用于下载给定 URL 的文件。它基本上只是 Linux 二进制“aria2c”的包装器。

这是名为getFile的脚本:

#!/usr/bin/python

#
# SCRIPT NAME: getFile
# PURPOSE: Download a file using up to 20 concurrent connections.
#

import os
import sys 
import re
import subprocess

try:
    fileToGet = sys.argv[1]

    if os.path.exists(fileToGet) and not os.path.exists(fileToGet+'.aria2'):
        print 'Skipping already-retrieved file: ' + fileToGet
    else:
        print 'Downloading file: ' + fileToGet
        subprocess.Popen(["aria2c-1.8.0", "-s", "20", str(fileToGet), "--check-certificate=false"]).wait() # SSL

except IndexError:
    print 'You must enter a URI.'

例如,这个命令会下载一个文件:

$ getFile http://upload.wikimedia.org/wikipedia/commons/8/8e/Self-portrait_with_Felt_Hat_by_Vincent_van_Gogh.jpg

我想要做的是允许一个可选的第二个参数(在 URI 之后),它是一个带引号的字符串。该字符串将是下载文件的新文件名。因此,下载完成后,文件将根据第二个参数重命名。使用上面的例子,我希望能够输入:

$ getFile http://upload.wikimedia.org/wikipedia/commons/8/8e/Self-portrait_with_Felt_Hat_by_Vincent_van_Gogh.jpg "van-Gogh-painting.jpg"

但我不知道如何将带引号的字符串作为可选参数。我该怎么做?

【问题讨论】:

    标签: python command-line-arguments argument-passing


    【解决方案1】:

    如果您在它们之间提供空格,shell 会将其作为第二个参数(通常)传递。

    例如这里是test.py:

    import sys
    
    for i in sys.argv:
        print(i)
    

    结果如下:

    $ python test.py url "folder_name"
    test.py
    url
    folder_name
    

    引号根本不重要,因为它是在 shell 中处理的,而不是在 python 中。要获得它,只需 sys.argv[2]

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      只测试sys.argv的长度;如果超过 2,则您有一个额外的参数:

      if len(sys.argv) > 2:
          filename = sys.argv[2]
      

      【讨论】:

      • 哦,所以如果你将一个带引号的字符串传递给 Python,它会自动将其视为单个参数?
      • 完全正确;引用是一个 shell 功能,与 Python 无关,真的。
      • 啊,好的,谢谢。我想我没有对这个问题进行尽职调查。我至少应该尝试一下,看看这些论点是如何起作用的,而不是假设它不会像你描述的那样起作用。 :) 所以,请原谅我的懒惰——非常感谢!
      • 或者使用argparse ... :)
      猜你喜欢
      • 2019-12-23
      • 2018-06-25
      • 2022-12-09
      • 2014-11-10
      • 2017-04-01
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 2015-09-13
      相关资源
      最近更新 更多