如何将字符串句子作为命令行参数传递

3
以下代码接受单个字符串值,可以在Python端检索。如何使用带有空格的句子字符串实现这一点?
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 the program runs",我想将其作为命令行参数传递并存储在‘first’变量中。


1
就像这样。test.py "Hello world the program runs" - Aran-Fey
因此,它需要引号 "",不像我的示例。 - Richard Smith
你的变量应该是 first 而不是 firstargument - jwillis0720
@RichardSmith,Python根本看不到这些引号;它们是由shell解释的,并告诉它如何将内容拆分成argv数组(再次强调,这是shell在启动Python之前执行的操作)。 - Charles Duffy
请参阅man execv,了解在UNIX上启动另一个程序所使用的C库调用家族 - 您将看到,在UNIX上启动另一个程序的任何程序都需要提供一组C字符串作为参数(该数组名为argv),除非使用基于varargs的调用约定,允许将该数组的每个元素作为独立的参数传递给调用。 - Charles Duffy
test.py Hello\ world\ the\ program\ runs,顺便说一下,这是一个完全等价的表达方式——也就是说,shell 调用了完全相同的内容,因此 Python 解释器无法区分两种调用方式之间的差异。对于 s='Hello world the program runs'; test.py "$s" 这种情况也是如此(但不包括 test.py $s)。 - Charles Duffy
2个回答

6

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

“如果您不想使用引号”版本存在漏洞。如果原始帖子中连续出现三个空格,它将被替换为一个空格;如果原始帖子中出现了 *,它将被替换为文件名列表等。当我们为那些事先不知道过程如何运作的人构建答案时,应该明确指出包含警告的答案。 - Charles Duffy
没错,有很多方法可以搞砸连接。但这只是提醒而已。 - jwillis0720
是的 - 我试图争论的重点是,这样一个FYI,其中方法实际上不能用于生产或不是良好的实践,应该在答案中明确指出,以便某人不会产生错误印象。 - Charles Duffy

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无关,而是与您的shell解析命令行参数的方式有关。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接