您正在使用的命令无法工作,因为单引号在 Windows 中没有特殊含义,它们按字面意思传递给 curl 程序。因此,如果您从 Linux 复制了命令行(它可以工作),这将无法在这里工作(虚假引号被传递给 curl,例如用于接收 'appuser 和 appuser!@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 函数):
- 检查返回代码,如果出错则引发异常
- 无需手动操作即可传递和引用参数。
让我们修正你的例子:
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 不在乎。如果参数中有空格,check_call 机制会自动处理参数保护/引用。
调用此脚本时,我得到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>