簡體   English   中英

用python中的請求編碼

[英]Encoding with requests in python

遇到一個奇怪的問題。

我將字典作為POST請求的一部分傳遞給cgi腳本:

self.settings = {
    'SubmitCommands': ['C:\Python27\python.exe path\my_script.py']
}

這是我的代碼:

    settings = self.settings

    # Make web call to CGI script
    user_agent = r'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = {'User-Agent' : user_agent, "Accept": "text/plain"}
    response = requests.post(
            "path\CGI\cgi_script.py", 
            headers=headers, data=settings)

這是結果回溯:

Traceback (most recent call last):
  File "path\CGI\cgi_script.py", line 119, in initi
alizeJob
    self.submitCommands = eval(inputSubmitCommands)
  File "<string>", line 1
    C:\Python27\python.exe path\my_script.py
     ^
SyntaxError: invalid syntax

但是,如果以老式方式執行此操作,則不會獲得回溯:

    settings = self.settings

    # Set and encode parameters
    params = urllib.urlencode(settings)

    # Make web call to CGI script
    user_agent = r'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = {'User-Agent' : user_agent,
                "Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/plain"}
    conn = httplib.HTTPConnection(self.host)
    conn.request("POST", "path/CGI/cgi_script.py", params, headers)
    response = conn.getresponse()

今天早些時候,有人在Stack Overflow上警告我選擇庫是因為它是新庫。 看來我應該聽他們的。 但是,我仍然對問題出在哪里感到好奇。

Python將反斜杠解釋為轉義代碼。 只需將它們加倍即可解決。

self.settings = {
    'SubmitCommands': ['C:\\Python27\\python.exe path\\my_script.py']
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM