commands.getstatusoutput("cmd")
等價於{ cmd ; } 2>&1
即stdout/stderr被合併。 curl
將http代碼打印到標準輸出。你可以使用subprocess.check_output
只得到標準輸出:
import shlex
from subprocess import check_output
DEVNULL = open(os.devnull, 'wb', 0)
curl_cmd = "curl -k --cookie ... -w %{http_code} -o filename 'URL'"
http_code = int(check_output(shlex.split(curl_cmd), stderr=DEVNULL))
正如其他人已經說過,你不需要啓動子,使Python中的http請求:你可以使用urllib2
,pycurl
,requests
庫,而不是如:
import urllib2
from shutil import copyfileobj
url = 'http://httpbin.org/status/418'
# to load cookies from file, you could use cookielib module
request = urllib2.Request(url, headers={'Cookie': 'cookie_name=value'})
try: # both `curl -k` and urllib2 do not verify ssl certificates
response = urllib2.urlopen(request)
except urllib2.HTTPError as e:
http_code = e.code
else:
http_code = response.code
print(http_code)
if http_code == 200: # save to file
with open('filename', 'wb') as output_file:
copyfileobj(response, output_file)
response.close()
來源
2014-05-16 22:51:41
jfs
你有什麼特別的理由使用Curl嗎?在Python中直接執行HTTP請求會更好也更容易(具有諸如請求或甚至內置的urllib或httplib之類的庫)。 –
我不知道具體的原因,因爲我試圖清理一些現有的代碼。我所知道的是它的https請求 – user2848437
在這種情況下,學習使用一些http相關的Python包,最簡單的方法就是使用'requests'。它可以讓你獲得狀態代碼和所有你需要的東西。 –