2011-01-08 36 views
0

我正在用Python 2.7編寫一個簡單的程序,使用pycURL庫將文件內容提交給pastebin。 這裏的程序代碼:關於Python中文件格式的新手問題

#!/usr/bin/env python2 

import pycurl, os 

def send(file): 
    print "Sending file to pastebin...." 
    curl = pycurl.Curl() 
    curl.setopt(pycurl.URL, "http://pastebin.com/api_public.php") 
    curl.setopt(pycurl.POST, True) 
    curl.setopt(pycurl.POSTFIELDS, "paste_code=%s" % file) 
    curl.setopt(pycurl.NOPROGRESS, True) 
    curl.perform() 

def main(): 
    content = raw_input("Provide the FULL path to the file: ") 
    open = file(content, 'r') 
    send(open.readlines()) 
    return 0 

main() 

輸出引擎收錄看起來像標準的Python列表:['string\n', 'line of text\n', ...]

有什麼辦法,所以它看起來更好,它實際上是人類可讀的,我可以格式化?另外,如果有人能告訴我如何在POSTFIELDS中使用多個數據輸入,我會非常高興。 Pastebin API使用paste_code作爲其主要數據輸入,但它可以使用諸如paste_name之類的可選事項來設置上傳的名稱或paste_private將其設置爲私有。

+0

我建議讓`POSTFIELDS`問題作爲一個單獨的問題。 – marcog 2011-01-08 13:35:12

回答

1
import pycurl, os 

def send(file_contents, name): 
    print "Sending file to pastebin...." 
    curl = pycurl.Curl() 
    curl.setopt(pycurl.URL, "http://pastebin.com/api_public.php") 
    curl.setopt(pycurl.POST, True) 
    curl.setopt(pycurl.POSTFIELDS, "paste_code=%s&paste_name=%s" \ 
            % (file_contents, name)) 
    curl.setopt(pycurl.NOPROGRESS, True) 
    curl.perform() 


if __name__ == "__main__": 
    content = raw_input("Provide the FULL path to the file: ") 
    with open(content, 'r') as f: 
     send(f.read(), "yournamehere") 
    print 

當讀取文件,使用with聲明(這可以確保你的文件被正確關閉,如果出現錯誤)。

沒有必要擁有main函數,然後調用它。使用if __name__ == "__main__"構造函數可以在調用時自動運行腳本(除非將其作爲模塊導入)。

對於發佈多個值,您可以手動構建url:只需使用&字符分隔不同的鍵值對(&)。像這樣:key1=value1&key2=value2。或者你可以用urllib.urlencode建立一個(如其他人所建議的)。

編輯:對字符串將被髮布使用urllib.urlencode使正常時源字符串中包含一些有趣的/保留/特殊字符確保內容進行編碼。

+1

只要記住urlencode`file_contents`和`name`。 – 2011-01-08 13:45:47

0

使用.read()而不是.readlines()

+0

請提供更多的解釋,一個人做什麼比另一個做什麼,爲什麼這個問題更有幫助。 – helion3 2014-02-02 05:08:59

3

首先,使用作爲.read()所述virhilo

另一步是使用urllib.urlencode()得到一個字符串:

curl.setopt(pycurl.POSTFIELDS, urllib.urlencode({"paste_code": file})) 

這也將讓您發佈多個字段:

curl.setopt(pycurl.POSTFIELDS, urllib.urlencode({"paste_code": file, "paste_name": name})) 
0

POSTFIELDS應sended相同的方式,你發送查詢字符串參數。所以,首先,需要將encode字符串發送到paste_code,然後使用&可以添加更多的POST參數。

例子:

paste_code=hello%20world&paste_name=test 

祝你好運!