0

我正在使用 pycURL 库在 Python 2.7 中编写一个简单的程序,以将文件内容提交到 pastebin。这是程序的代码:

#!/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()

输出的 pastebin 看起来像标准的 Python 列表:['string\n', 'line of text\n', ...]等等。

有什么办法可以格式化它,让它看起来更好,而且它实际上是人类可读的?另外,如果有人能告诉我如何在POSTFIELDS. Pastebin APIpaste_code用作其主要数据输入,但它可以使用可选的东西paste_name,例如设置上传的名称或paste_private将其设置为私有。

4

4 回答 4

3

首先,.read()virhilo上述方式使用。

另一个步骤是用来urllib.urlencode()获取字符串:

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

This will also allow you to post more fields:

curl.setopt(pycurl.POSTFIELDS, urllib.urlencode({"paste_code": file, "paste_name": name}))
于 2011-01-08T13:39:53.000 回答
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

When reading files, use the with statement (this makes sure your file gets closed properly if something goes wrong).

There's no need to be having a main function and then calling it. Use the if __name__ == "__main__" construct to have your script run automagically when called (unless when importing this as a module).

For posting multiple values, you can manually build the url: just seperate different key, value pairs with an ampersand (&). Like this: key1=value1&key2=value2. Or you can build one with urllib.urlencode (as others suggested).

EDIT: using urllib.urlencode on strings which are to be posted makes sure content is encoded properly when your source string contains some funny / reserved / unusual characters.

于 2011-01-08T13:40:32.970 回答
0

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

于 2011-01-08T13:35:01.987 回答
0

The POSTFIELDS should be sended the same way as you send Query String arguments. So, in the first place, it's necessary to encode the string that you're sending to paste_code, and then, using & you could add more POST arguments.

Example:

paste_code=hello%20world&paste_name=test

Good luck!

于 2011-01-08T13:39:57.720 回答