"substring not found" 即使它包含在命令行传递的参数中
"substring not found" even though it's included in the argument passed on the command line
我不明白为什么会这样,所以感谢您的帮助。
hi.py
import httplib, urlparse, sys, urllib
url = sys.argv[1]
print url
print url.index("token")
print url.index("&user")
然后在 ubuntu 中,如果我尝试 运行 类似于:
python hi.py http://somewebsite.com/api?token=hello_world&user=myself
我得到这个作为输出:
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
出于某种原因,整个 URL 没有被打印出来,我怀疑这就是找不到 &user 子字符串的原因。有什么想法吗?
&
是一个 shell 元字符,即 puts the command in the background。您需要 引用 您的论点以防止 &
字符被这样解释:
python hi.py "http://somewebsite.com/api?token=hello_world&user=myself"
或使用 \
反斜杠仅转义 & 符号:
python hi.py http://somewebsite.com/api?token=hello_world\&user=myself
否则 shell 将其视为两个单独的命令,巧合的是 user=myself
是有效的 shell 语法。
以下任一字符为special in a shell:
\ ' " ` < > | ; <Space> <Tab> <Newline> ( ) [ ] ? # $ ^ & * =
这些都需要用同样的方式进行转义; ?
恰好适用于 URL,因为没有文件名被匹配;如果您使用 hi.p?
,文件名 hi.py
将被替换。我认为 =
仅当左侧是有效的 shell 变量标识符时才需要转义,但为了安全起见,我会坚持引用整个 URL.
我不明白为什么会这样,所以感谢您的帮助。
hi.py
import httplib, urlparse, sys, urllib
url = sys.argv[1]
print url
print url.index("token")
print url.index("&user")
然后在 ubuntu 中,如果我尝试 运行 类似于:
python hi.py http://somewebsite.com/api?token=hello_world&user=myself
我得到这个作为输出:
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
出于某种原因,整个 URL 没有被打印出来,我怀疑这就是找不到 &user 子字符串的原因。有什么想法吗?
&
是一个 shell 元字符,即 puts the command in the background。您需要 引用 您的论点以防止 &
字符被这样解释:
python hi.py "http://somewebsite.com/api?token=hello_world&user=myself"
或使用 \
反斜杠仅转义 & 符号:
python hi.py http://somewebsite.com/api?token=hello_world\&user=myself
否则 shell 将其视为两个单独的命令,巧合的是 user=myself
是有效的 shell 语法。
以下任一字符为special in a shell:
\ ' " ` < > | ; <Space> <Tab> <Newline> ( ) [ ] ? # $ ^ & * =
这些都需要用同样的方式进行转义; ?
恰好适用于 URL,因为没有文件名被匹配;如果您使用 hi.p?
,文件名 hi.py
将被替换。我认为 =
仅当左侧是有效的 shell 变量标识符时才需要转义,但为了安全起见,我会坚持引用整个 URL.