【发布时间】:2011-12-22 16:18:41
【问题描述】:
我需要执行一个shell脚本来通过python命令运行python程序。
我应该像这样执行我的 python 脚本
ubuntu@ip-10-32-157-231:~/hg_intcen/lib$ xvfb-run python webpage_scrapper.py http://www.google.ca/search?q=navaspot
此脚本需要在 python 程序中执行,因为必须将大量链接传递给该模块。
我已经搜索过在 python 中执行这个 shell 脚本,所以我使用了“子进程”
主要是当你运行这个 shell 命令时,它需要一些时间来返回结果。 我需要python模块来执行这个命令,并且它必须等待一段时间才能返回结果。这是必需的。
我使用了 subprocess.Popen 它不会像我从 bash 得到的那样返回结果
import subprocess
def execute_scrapping(url):
exe_cmd = "xvfb-run python lib/webpage_scrapper.py"+" "+str(url)
print "cmd:"+exe_cmd
proc = subprocess.Popen(exe_cmd,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
time.sleep(15)
sys.stdout.flush()
d=proc.stdout.readlines()
return d[1]
上面的这个没有遇到确切的结果。 你能建议我通过python执行bash shell命令并得到结果吗?
【问题讨论】:
-
从 within Python 运行 Python?啊。您是否有任何理由无法导入该脚本并将其用作模块?
-
是的,当然。原因是“xvfb-run”。它只执行我的 python 模块。xvfb 是 x 虚拟帧缓冲区。与 xvfb 一起,只有该模块会给出结果。
-
您可以将 xvfb-run 替换为 PyVirtualDisplay。然后你可以导入webpage_scrapper.py 而不是使用子进程。
-
@unutbu 它也不能与 pyvirtualdisplay 一起使用..xvfb 命令只能这样做 这是有什么错误吗? >>> from pyvirtualdisplay import Display >>> Display(visible=1, size=(320, 240)).start() >>> crawl(url) manage.py: cannot connect to X server :1188
标签: python bash shell ubuntu-11.04 subprocess