2014-05-03 40 views
0
status, output = commands.getstatusoutput("curl -k -v --cookie cookie_name 'URL' -o filename") 

上面是我的代碼,我試圖返回curl的http響應代碼。所以我嘗試了以下選項-w%{http_code}返回http在python中捲曲的錯誤代碼

status, output = commands.getstatusoutput("curl -k -v --cookie cookie_name -w %{http_code} 'URL' -o filename") 

當我在python腳本和打印狀態下運行它時,沒有任何打印。 有人可以幫我用curl返回代碼嗎? 我想嘗試一下場景,比如當用戶名密碼錯誤以獲取狀態,或者網絡主機無法訪問或內容未正確下載時。

+0

你有什麼特別的理由使用Curl嗎?在Python中直接執行HTTP請求會更好也更容易(具有諸如請求或甚至內置的urllib或httplib之類的庫)。 –

+0

我不知道具體的原因,因爲我試圖清理一些現有的代碼。我所知道的是它的https請求 – user2848437

+0

在這種情況下,學習使用一些http相關的Python包,最簡單的方法就是使用'requests'。它可以讓你獲得狀態代碼和所有你需要的東西。 –

回答

0

正如其他人建議的那樣,最好使用HTTP來執行卷曲調用。 requests是最簡單的方法:

import requests 

data = { 
    ... 
} 
r = requests.post(url, data=data) 
print r.content 

r.content包含響應體,如果你需要的狀態代碼只使用r.status_code

+0

感謝您的回覆。但我需要使用捲曲,因爲這涉及cookie傳輸 – user2848437

+0

@ user2848437 http://docs.python-requests.org/en/latest/user/quickstart/#cookies – AliBZ

0

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請求:你可以使用urllib2pycurlrequests庫,而不是如:

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()