python - 在 python 中运行 shell 脚本

标签 python bash shell ubuntu-11.04 subprocess

我需要执行一个 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/

相关文章:

python - 在数组中执行正则表达式搜索时,它返回为空

python - 如何使用 Altair 进行注释?

bash - 本地机器覆盖的 Docker 镜像环境变量

linux - 将 1000 字节转换为 1024 字节

shell - 如何更改AWS Cognito用户的密码?

python - 无法使用唯一的第一个键确定性地更新嵌套字典

python - 从索引对创建倍数的元组

bash - 如何从 bash 中的文件循环打印 2 列

bash 字符串比较失败

mysql - 如何在shell脚本中将查询的结果集插入到表中?