在Python中运行Shell脚本

1 投票
2 回答
3987 浏览
提问于 2025-04-17 08:51

我需要执行一个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命令并获取结果吗?

2 个回答

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')
8

试试这个:

proc.wait()

替代你原来的 time.sleep(15) 这行代码。

根据文档说明:

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

撰写回答