Python 打开多个 URL 连接 - urllib2

发布于 2024-10-06 02:15:33 字数 392 浏览 1 评论 0原文

我正在尝试创建一个 python 脚本,它允许我加载多个连接,类似于在浏览器上打开多个选项卡,更明确地说,我有这样的代码:

https://github.com/eWizardII/SOC357-Twitter-Facebook-Project/blob/master/chuck.py< /a>

使用 urlv 等,我加载了与 API 的多个连接,但是我希望能够同时调用所有 5 个连接,而不是连续调用。我研究过扭曲和整齐之类的东西,但我不知道如何使用它们来帮助我。

谢谢, 所罗门

I'm trying to create a python script that will allow me to load up multiple connections similar to having multiple tabs open on a browser, more explicitly I have a code like this:

https://github.com/eWizardII/SOC357-Twitter-Facebook-Project/blob/master/chuck.py

Using urlv, etc, I load up multiple connections to the API, however I want to make it so that I call all 5 at the same time instead of in succession. I have looked into things like twisted and tidy, but I don't know how to use them to help me.

Thanks,
Solomon

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

爱的故事 2024-10-13 02:15:33

使用外壳。

#!/bin/bash
python chuck.py "request 1" &
python chuck.py "request 2" &
python chuck.py "request 3" &
python chuck.py "request 4" &
python chuck.py "request 5" &

这将运行您的程序的 5 个副本。它将占用尽可能多的内核和 CPU。而且——额外的好处——没有使用子进程或线程或任何东西进行编程。

如果所有 5 个人都应该做不同的事情,那么你就必须提供某种参数或选项。查看 argparse 来获取收集命令行参数的方法。

Use the shell.

#!/bin/bash
python chuck.py "request 1" &
python chuck.py "request 2" &
python chuck.py "request 3" &
python chuck.py "request 4" &
python chuck.py "request 5" &

This will run 5 copies of your program. It will tie up as many cores and CPUs as it can. And -- bonus -- no programming using subprocess or threading or anything.

If all 5 are supposed to do somehow different things, then you'll have to provide some kind of arguments or options. Look into argparse for a way to gather command-line arguments.

带上头具痛哭 2024-10-13 02:15:33

您可以创建 HttpHandler 来处理异步 http 请求(就您的代码而言是异步的,而不是实际网络操作时的异步)。

试试这个:

import urllib2

class MyHttpHandler(urllib2.HTTPHandler):
    def http_response(self, request, response):
        for l in response:
            print l
        return response

u = urllib2.build_opener(MyHttpHandler())
for i in range(1, 5):
    u.open('http://stackoverflow.com')

You can create HttpHandlers to handle asynchronous http requests (asynchronous as far as your code is concerned, not when it comes to actual network operations).

Try this:

import urllib2

class MyHttpHandler(urllib2.HTTPHandler):
    def http_response(self, request, response):
        for l in response:
            print l
        return response

u = urllib2.build_opener(MyHttpHandler())
for i in range(1, 5):
    u.open('http://stackoverflow.com')
我不吻晚风 2024-10-13 02:15:33

您可以使用线程库。这是它最适合的事情之一。

You can use the threading library. That is one of the things it is best suited.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文