我需要执行一个 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 脚本,所以我使用了“subprocess”
最主要的是,当您运行此 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 命令并获取结果?
最佳答案
尝试:
proc.wait()
而不是你的 time.sleep(15)
调用。
来自文档:
Popen.wait() - Wait for child process to terminate. Set and return returncode attribute.
关于python - 在 python 中运行 shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8606709/