2011-01-08 59 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 

祝你好运!