如何在 Python 中执行 Curl

How to execute Curl in Python

我正在尝试在 python 脚本中执行 curl 命令,但无法传递带符号的密码。

import os;
os.system("curl -H 'Content-Type: text/xml;charset=UTF-8' -u 'appuser:appuser!@3pass' -i -v 'http://app.com/webservice/getUserData' -o userdata.xml")

我在 return 中收到拒绝访问消息,用户名和密码正确。我想这是因为密码中的特殊字符。 我试过转义像 appuser\!\@3pass 这样的字符,但没有帮助。

谁能指导一下?

您正在使用的命令无法工作,因为单引号在 Windows 中没有特殊含义,它们按字面意思传递给 curl 程序。因此,如果您从 Linux(它可以工作的地方)复制了命令行,那么它在这里将不起作用(虚假引号被传递给 curl,例如 login/password 字段接收 'appuserappuser!@3pass',还有 Content-Type: text/xml;charset=UTF-8 根本不受保护,被理解为 2 个单独的参数)

从控制台进行简单测试:

K:\progs\cli>curl.exe -V
curl 7.50.3 (x86_64-pc-win32) libcurl/7.50.3 OpenSSL/1.0.2h nghttp2/1.14.1
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtsp smb smbs smtp smtps
telnet tftp
Features: AsynchDNS IPv6 Largefile NTLM SSL HTTP2

(如果我使用带双引号的 "-V" 也有效),但如果我在版本 arg 上使用简单引号,我得到:

K:\progs\cli>curl.exe '-V'
curl: (6) Could not resolve host: '-V'

正如 o11c 评论的那样,有一个 python 模块来处理 curl,你最好使用它。

对于其他无法使用的情况,不推荐使用 os.system。例如使用subprocess.check_call更好(python 3.5有统一的run功能):

  • return 代码已检查,如果出错则引发异常
  • 无需手动操作即可传递和引用参数的能力。

让我们修正你的例子:

subprocess.check_call(["curl","-H","Content-Type: text/xml;charset=UTF-8","-u",'appuser:appuser!@3pass',"-i","-v",'http://app.com/webservice/getUserData',"-o","userdata.xml"])

请注意,我故意混合了单引号和双引号。 Python 不在乎。如果参数中有 space,check_call 机制会设法自动处理参数 protection/quoting。

调用此脚本时,我得到 userdata.xml 填写如下:

HTTP/1.1 301 Moved Permanently
Date: Fri, 15 Sep 2017 20:49:50 GMT
Server: Apache
Location: http://www.app.com/webservice/getUserData
Content-Type: text/html; charset=iso-8859-1
Transfer-Encoding: chunked

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://www.app.com/webservice/getUserData">here</a>.</p>
</body></html>