gpt4 book ai didi

python - "substring not found"即使它包含在命令行上传递的参数中

转载 作者:行者123 更新时间:2023-12-04 18:58:00 24 4
gpt4 key购买 nike

我不知道为什么会这样,所以任何帮助表示赞赏。

嗨.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。

关于python - "substring not found"即使它包含在命令行上传递的参数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com