如何使用 os.system() 从标准输入获取数据

发布于 2024-07-10 03:59:44 字数 158 浏览 10 评论 0原文

我发现使用脚本从维基百科下载文本的唯一可靠方法是使用 cURL。 到目前为止,我唯一的方法就是调用 os.system()。 尽管输出在 python shell 中正确显示,但我似乎无法返回除退出代码(0)之外的任何内容。 或者有人可以展示如何正确使用 urllib。

The only reliable method that I a have found for using a script to download text from wikipedia is with cURL. So far the only way I have for doing that is to call os.system(). Even though the output appears properly in the python shell I can't seem to the function it to return anything other than the exit code(0). Alternately somebody could show be how to properly use urllib.

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

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

发布评论

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

评论(3

走走停停 2024-07-17 03:59:44

来自 深入了解 Python:

import urllib
sock = urllib.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
htmlsource = sock.read()
sock.close()
print htmlsource

这将打印出 Python 维基百科文章的源代码。 我建议您查看 Dive into Python 了解更多详细信息。

使用 Python 库参考中的 urllib2 的示例:

import urllib2
f = urllib2.urlopen('http://www.python.org/')
print f.read(100)

编辑:您也可能想看看 wget。
Edit2:根据 S.Lott 的建议添加了 urllib2 示例

From Dive into Python:

import urllib
sock = urllib.urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
htmlsource = sock.read()
sock.close()
print htmlsource

That will print out the source code for the Python Wikipedia article. I suggest you take a look at Dive into Python for more details.

Example using urllib2 from the Python Library Reference:

import urllib2
f = urllib2.urlopen('http://www.python.org/')
print f.read(100)

Edit: Also you might want to take a look at wget.
Edit2: Added urllib2 example based on S.Lott's advice

那请放手 2024-07-17 03:59:44

回答问题,
Python 有一个子进程模块,允许您与生成的进程进行交互。http:// docs.python.org/library/subprocess.html#subprocess.Popen

它允许您读取调用进程的标准输出,甚至将项目发送到标准输入。

然而正如你所说, urllib 是一个更好的选择。 如果您搜索 stackoverflow,我相信您会发现至少 10 个其他相关问题...

Answering the question,
Python has a subprocess module which allows you to interact with spawned processes.http://docs.python.org/library/subprocess.html#subprocess.Popen

It allows you to read the stdout for the invoked process, and even send items to the stdin.

however as you said urllib is a much better option. if you search stackoverflow i am sure you will find at least 10 other related questions...

温柔一刀 2024-07-17 03:59:44

作为 urllib 的替代方案,您可以使用 libCurl Python 绑定

As an alternetive to urllib, you could use the libCurl Python bindings.

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