【问题标题】:Run shell script in python在python中运行shell脚本
【发布时间】: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


【解决方案1】:

试试:

proc.wait()

而不是您的time.sleep(15) 电话。

来自文档:

Popen.wait() - 等待子进程终止。设置并返回返回码属性。

【讨论】:

    【解决方案2】:

    您应该使用 communicate() 方法等待外部进程完成。

    stddata, stderr = proc.communicate()
    

    如果您必须在两个进程之间交换消息,请查看pexpect 模块:

    来自网站:

       import pexpect
       child = pexpect.spawn ('ftp ftp.openbsd.org')
       child.expect ('Name .*: ')
       child.sendline ('anonymous')
       child.expect ('Password:')
       child.sendline ('noah@example.com')
       child.expect ('ftp> ')
       child.sendline ('cd pub')
       child.expect('ftp> ')
       child.sendline ('get ls-lR.gz')
       child.expect('ftp> ')
       child.sendline ('bye')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 2013-01-05
      • 2020-01-01
      • 2021-12-15
      • 1970-01-01
      相关资源
      最近更新 更多