python 运行 os.system() 时意外的 EOF

python unexpected EOF when running os.system()

任务: 我正在尝试 运行 python 中的系统命令。该命令是 IFTTT 的 webhook,它向我的 phone 发送通知。我关注了这篇文章here

我尝试通过 bash 对它进行 运行 设置,但在参数格式方面运气不佳(我根本不知道 bash)。所以我使用 python。这是我的代码。

import os
command = """curl -X POST -H "Content-Type: application/json" -d '{"value1":"I'm frustrated"}' https://maker.ifttt.com/trigger/notify_phone/with/key/<my_key>"""
os.system(command)

请注意我对 json 的“价值 1”是“我很沮丧”。计算机无法识别 I'm 中的单引号,我也不知道为什么。我收到以下错误:

sh: -c: line 0: unexpected EOF while looking for matching `"'
sh: -c: line 1: syntax error: unexpected end of file

我也尝试了以下命令,但遇到了同样的错误,所以我真的很困惑。

command = """curl -X POST -H "Content-Type: application/json" -d '{"value1":"I\'m frustrated"}' https://maker.ifttt.com/trigger/notify_phone/with/key/<my_key>"""

command = """curl -X POST -H "Content-Type: application/json" -d '{"value1":"I\'m frustrated"}' https://maker.ifttt.com/trigger/notify_phone/with/key/<my_key>"""

我做错了什么?

I tried running it via bash but didn't have much luck with the argument formatting (I don't know bash, at all). So instead I am using python.

啊,但是您正在使用 os.system,它在子 shell 中运行,所以您仍在使用 shell,可能是 bash 或等效项.所以你没有避免同样的逃脱挑战。

Task: I'm trying to run a system command in python.

看你的问题,我认为你实际任务是发出网络请求。

curl -X POST -H "Content-Type: application/json" -d '{"value1":"I'm frustrated"}' https://maker.ifttt.com/trigger/notify_phone/with/key/<my_key>

好的,您正在制作 Json 数据的 HTTP POST。如果您对 python 感到满意,为什么要调用不同的可执行文件来发出 HTTP 请求? requests 是在 python.

中最常见的做法

从那个 link 中的例子开始,类似于

r = requests.post('https://maker.ifttt.com/trigger/notify_phone/with/key/<my_key>', data={'value1':'I\'m frustrated'})

-H "Content-Type: application/json"

我相信当您将对象作为数据传递时,您会免费获得它。但是肯定可以使用 requests.

显式设置它

就其价值而言,您遇到的转义问题是 bash 语法的一个怪癖:\' 不会转义单引号字符串中的单引号。将 bash 中的 ' 想象成一个“开关”;一个 ' 禁用特殊字符,另一个 ' 重新启用它们。由于 \ 是短语 '\'' 中的特殊字符,因此它不是有效的表达式。

彼得伍德说,

It's better to build commands using subprocess so they get escaped/quoted correctly.

subprocessos.system 效果好得多的原因是因为您可以在调用中将参数指定为单独的值,因此您不需要为 shell 本身。事实上,你没有 需要 shell 来调用 curl.

subprocess.run(["curl", "-X", "POST", ..., ... ], capture_output=True)

您的 POST 数据仍需格式化为有效 json:

... '-d', '{"value1":"I\'m frustrated"}'

Python 对 '.

进行了合理的标准引用转义
>>> print('I\'m working')
I'm working

如果您真的想在 bash shell 秒内完成此操作,可以通过多种机制实现。这是一个:

curl -X POST -H "Content-Type: application/json" -d '{"value1":"I'\''m frustrated"}' http://httpbin.org/post

但重申一下,只需使用 python 的请求即可。它将正确处理您的 Json 数据编码,如果您应该关心 Web 请求的 return,那么在请求中处理该数据将是 比处理 curl 的输出要容易得多