[英]How to pass a String sentence as Command Line Argument
以下代码采用单个String值,可以在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
输入的示例可能是“程序正在运行的世界”,我想将其作为命令行参数传递给存储在“ first”变量中。
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
多字命令行参数,即包含由空格字符%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解析命令行参数的方式有关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.