[英]“substring not found” even though it's included in the argument passed on the command line
I can't figure out why this is happening, so any help is appreciated. 我无法弄清楚为什么会发生这种情况,因此可以提供任何帮助。
hi.py 嗨
import httplib, urlparse, sys, urllib
url = sys.argv[1]
print url
print url.index("token")
print url.index("&user")
Then in ubuntu if I try to run something like: 然后在ubuntu中,如果我尝试运行以下命令:
python hi.py http://somewebsite.com/api?token=hello_world&user=myself
I get this as output: 我得到这个作为输出:
http://somewebsite.com/api?token=hello_world
27
Traceback (most recent call last):
File "hi.py", line 10, in <module>
print url.index("&user")
ValueError: substring not found
For some reason the whole URL is not being printed, and I suspect that's why the &user substring is not found. 由于某种原因,没有打印出整个URL,我怀疑这就是为什么未找到&user子字符串的原因。 Any ideas?
有任何想法吗?
&
is a shell meta character, which puts the command in the background . &
是一个外壳元字符, 它将命令放在后台 。 You need to quote your argument to prevent the &
character from being interpreted as such: 您需要引用参数以防止
&
字符被解释为:
python hi.py "http://somewebsite.com/api?token=hello_world&user=myself"
or use a \\
backslash to escape just the ampersand: 或使用
\\
反斜杠以仅跳过&符:
python hi.py http://somewebsite.com/api?token=hello_world\&user=myself
otherwise the shell sees this as two separate commands, with user=myself
by coincidence being valid shell syntax. 否则,shell将其视为两个单独的命令,其中
user=myself
是巧合的有效shell语法。
Any of the following characters are special in a shell : 以下任何字符在shell中都是特殊的 :
\ ' " ` < > | ; <Space> <Tab> <Newline> ( ) [ ] ? # $ ^ & * =
These need to be escaped in the same way; 这些需要以相同的方式进行逃避; the
?
?
happens to work for the URL since no filenames are being matched; 由于没有匹配的文件名,因此碰巧适用于该URL; had you used
hi.p?
您使用过
hi.p?
the filename hi.py
would be substituted. 文件名
hi.py
将被替换。 The =
only needs escaping when the left-hand side is a valid shell variable identifier I think, but to be safe I'd stick with quoting the whole URL. =
仅当左侧是我认为有效的外壳变量标识符时才需要转义,但为安全起见,我坚持引用整个URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.