在 python 中运行 shell 脚本
我需要执行一个 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 命令并得到结果吗?
I need to execute a shell script to run the python program in via python command.
I should have to execute my python script like this
ubuntu@ip-10-32-157-231:~/hg_intcen/lib$ xvfb-run python webpage_scrapper.py http://www.google.ca/search?q=navaspot
This script need to be executed in python program since there are huge links has to be passed to that module.
I have searched to execute this shell script in python,so i used "subprocess"
The main thing is when you run this shell command it takes some time to return the result.
i need the python module to execute this command as well as it has to wait for while to return the result.This is required.
I used subprocess.Popen it doesn't return the result like what i got from the 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]
this above is not run into exact result.
Could you please suggest me to execute the bash shell command via python and get the result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试:
而不是您的
time.sleep(15)
调用。来自文档:
Try:
instead of your
time.sleep(15)
call.From the docs:
您应该使用communicate() > 等待外部进程完成的方法。
如果您必须在两个进程之间交换消息,请查看 pexpect 模块:
从网站:
You should use the communicate() method to wait that the external process completes.
If you have to exchange messages between the two process then look into the pexpect module:
From the website: