如何将String语句作为命令行参数传递

时间:2017-03-06 11:59:25

标签: python shell argparse

以下代码采用可在Python端检索的单个String值。如何使用带空格的句子字符串?

from sys import argv

script, firstargument = argv

print "The script is called:", script
print "Your first variable is:", firstargument

要运行我会传递参数:

$ python test.py firstargument

哪个会输出

The script is called:test.py
Your first variable is:firstargument

示例输入可以是"程序运行的Hello world"我希望将其作为命令行参数传递,以存储在' first'变量

2 个答案:

答案 0 :(得分:3)

argv将是shell解析的所有参数的列表。

所以,如果我做

#script.py
from sys import argv
print argv

$python script.py hello, how are you
['script.py','hello','how','are','you]

脚本的名称始终是列表中的第一个元素。如果我们不使用引号,则每个单词也将成为列表中的元素。

print argv[1]
print argv[2]
$python script.py hello how are you
hello
how

但如果我们使用引号,

$python script.py "hello, how are you"
 ['script.py','hello, how are you']

所有单词现在都是列表中的一个项目。所以做这样的事情

print "The script is called:", argv[0] #slicing our list for the first item
print "Your first variable is:", argv[1]

或者,如果您因某些原因不想使用引号:

print "The script is called:", argv[0] #slicing our list for the first item
print "Your first variable is:", " ".join(argv[1:]) #slicing the remaining part of our list and joining it as a string.

$python script.py hello, how are you
$The script is called: script.py
$Your first variable is: hello, how are you

答案 1 :(得分:1)

多字命令行参数,即包含由空格字符%20分隔的多个ASCII序列的单值参数,必须在命令行中用引号括起来。

$ python test.py "f i r s t a r g u m e n t"
The script is called:test.py
Your first variable is:f i r s t a r g u m e n t

这实际上与Python无关,而是与your shell parses the command line arguments.

的方式有关