导航:首页 > 程序命令 > python执行shell命令

python执行shell命令

发布时间:2022-10-23 05:19:41

‘壹’ python中怎么运行shell脚本

python中怎么运行shell脚本?
system()
其中最后一个0是这个命令的返回值,为0表示命令执行成功。使用system无法将执行的结果保存起来。
popen()
获取命令执行的结果,但是没有命令的执行状态,这样可以将获取的结果保存起来放到pst中。
commands
可以很方便的取得命令的输出(包括标准和错误输出)和执行状态位。
commands.getoutput('ls')这个方法只返回执行结果result不返回状态。
在python中调用shell脚本
hello.sh
下面的512是返回的状态码,如果eixt 0时则返回的是0.
shell脚本使用python脚本的参数
写一个hello.sh脚本,需要传入两个参数:
执行结果如下:
在python脚本中调用shell脚本,并传入参数,注意参数前后要有空格
执行python脚本
相关推荐:《Python教程》以上就是小编分享的关于python中怎么运行shell脚本的详细内容希望对大家有所帮助,更多有关python教程请关注环球青藤其它相关文章!

‘贰’ python执行shell命令和java执行shell命令的区别

没区别。。。
因为都是调用的同一个东西,能有区别吗?

‘叁’ python中的shell提示符是什么意思

命令行的shell直接输入你要输入的东西就行。

Shell 循环

启动 shell 时,它会立刻展示命令提示符并等待输入。在接收到命令并执行完毕(细节会在后面讲到)后,shell 会再次回到等待循环,准备接收下一条命令。

在shell.py中,我们通过主函数调用shell_loop()函数,来启动循环。代码如下:

然后在shell_loop()函数中,使用status标志来表示循环是否应该继续。在循环开始时,shell 将立即显示命令提示符,并等待输入。

(3)python执行shell命令扩展阅读

用户在 shell 中键入命令并按下回车时,输入的命令是一条长长的字符串,其中包含了命令名以及参数。因此,我们必须将其切分(将字符串拆分成多个 token)。

字符串切分乍一看很简单。我们可能会使用cmd.split()根据空格来分割输入的命令。对于形如ls -a my_folder的命令是奏效的,因为cmd.split()会将其拆分为一个列表 —['ls', '-a', 'my_folder’],这样我们使用起来就比较容易了。

但是,某些情况下,某些参数会带有单引号或者双引号,比如echo "Hello World”或者echo 'Hello World’。如果我们使用cmd.split(), 将会得到一个包含三个 token 的列表 —['echo', '"Hello', 'World”’],而不是包含两个 token 的列表 —['echo', 'Hello World’]。

‘肆’ 如何使用python执行远程shell脚本

最近有个需求就是页面上执行shell命令,第一想到的就是os.system,

代码如下:
os.system('cat /proc/cpuinfo')

但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了。

尝试第二种方案 os.popen()

代码如下:
output = os.popen('cat /proc/cpuinfo')
print output.read()

通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是无法读取程序执行的返回值)

尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。

代码如下:
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output

Python Document 中给的一个例子,

代码如下:
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

‘伍’ 我希望通过Python脚本实现多次执行shell命令

python脚本实现多次循环执行shell命令有三种方法,代码如下:

#方法一
os.system
importos
i=0
whileTrue:
i=i+1
os.system("tcpreplay-ibond0-M5-l1oracle_request_response.cap")
print"+++++++++++++++++++++++++++++++"
print"times:",i
time.sleep(5)

#方法二
os.popen
importos
i=0
whileTrue:
i=i+1
printos.popen("tcpreplay-ibond0-M5-l1oracle_request_response.cap").read()
print"+++++++++++++++++++++++++++++++"
print"times:",i
time.sleep(60)

#方法三
output=Popen("xxx",shell=True).communicate()[0]
importos
fromsubprocessimport*
i=0
whileTrue:
i=i+1
output=Popen("tcpreplay-ibond0-M5-l1oracle/*",shell=True).communicate()[0]
print"+++++++++++++++++++++++++++++++"
print"times:",i
time.sleep(60)

‘陆’ 什么是python shell 命令

python shell不是特指某一项命令,而是一种命令行环境。可以在shell里面导包、执行语句,常见的有 ipython环境,比python自带的shell要好得多。安装方式:pip install ipython

‘柒’ python shell怎么使用

Python 中执行 Shell 命令有多种方法,stackoverflow 上有对这些方法进行比较的讨论,Calling an external command in Python 指出使用subprocess模块来实现更优。因此,本文说明如何使用subprocess模块来实现 Shell 脚本的功能。
subprocess模块提供多种方法来实现执行 Linux 的命令,例如subprocess.call()方法,subprocess.check_call()方法,等。这些方法都是对Popen类的封装,故本文着重讲述Popen类的使用。

执行 Shell 命令
可以通过向Popen()传递需要执行的命令来创建一个Popen对象,这样,便会创建一个子进程来执行命令。例如:

child = subprocess.Popen(["ping","-c","5","leehao.me"])
1
上面的代码会创建一个子进程来执行ping -c 5 leehao.me命令,这个命令采用列表的形式传递给Popen()方法。如果我们想直接采用ping -c 5 leehao.me字符串形式,可以添加shell=True来实现:

child = subprocess.Popen("ping -c 5 leehao.me", shell=True)
1
官方文档指出由于安全原因故不建议使用shell=True,详细说明可以参考官方文档的描述。

等待子进程执行
子进程执行命令后,主进程并不会等待子进程执行。为了让主进程等待子进程执行结束,需要显示调用Popen.wait()方法。例如:

child = subprocess.Popen(["ping","-c","5","leehao.me"])
child.wait()
print 'parent finish'
1
2
3
这样,主进程会等待子进程执行ping命令完毕后,才会打印出parent finish的输出。

获取执行结果
为了获取Popen()子进程的输出,可以使用Popen.communicate()方法,例如:

def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout

subprocess_cmd('echo leehao.me; echo www.leehao.me')
1
2
3
4
5
6
输出:

leehao.me
www.leehao.me

process.communicate()方法可以实现主进程与子进程的通信。主进程可以通过它向子进程发送数据,也可以读取子进程的输出的数据。上面的例子中,我们在创建Popen对象时指定stdout=subprocess.PIPE,这样主进程便可以读取子进程的输出。
communicate()方法返回一个元组:(stdoutdata, stderrdata),process.communicate()[0]即获取子进程的标准输出。
需要指出的是,调用communicate()方法后,主进程也会等待子进程执行完毕。
上面的例子中,子进程向标准输出打印两个字符串,主进程接收到了这些输出,并打印出来。

‘捌’ 如何python 中运行scapy shell

启用shell
可以使用如下命令启用shell
[python] view plain
scrapy shell <url>
其中<url>就是你想抓取的页面url

使用shell
Scrapy shell可以看成是一个内置了几个有用的功能函数的python控制台程序。

功能函数
shelp() - 输出一系列可用的对象和函数
fetch(request_or_url)-从给定的url或既有的request请求对象重新生成response对象,并更新原有的相关对象
view(response)-使用浏览器打开原有的response对象(换句话说就是html页面)
Scrapy 对象
使用Scrapy shell下载指定页面的时候,会生成一些可用的对象,比如Response对象和Selector对象(Html和XML均适用)
这些可用的对象有:

crawler - 当前的Crawler对象
spider
request - 最后获取页面的请求对象
response - 一个包含最后获取页面的响应对象
sel - 最新下载页面的Selector对象
settings - 当前的Scrapy settings
Scrapy shell例子
以我的个人博客作为测试:http://blog.csdn.net/php_fly
首先,我们启动shell
[python] view plain
scrapy shell http://blog.csdn.net/php_fly --nolog
以上命令执行后,会使用Scrapy downloader下载指定url的页面数据,并且打印出可用的对象和函数列表

[python] view plain
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x0000000002AEF7B8>
[s] item {}
[s] request <GET http://blog.csdn.net/php_fly>
[s] response <200 http://blog.csdn.net/php_fly>
[s] sel <Selector xpath=None data=u'<html xmlns="http://www.w3.org/1999/xhtm'>
[s] settings <CrawlerSettings mole=None>
[s] spider <Spider 'default' at 0x4cdb940>
[s] Useful shortcuts:
[s] shelp() Shell help (print this help)
[s] fetch(req_or_url) Fetch request (or URL) and update local objects
[s] view(response) View response in a browser
获取曾是土木人博客的文章列表超链接
[python] view plain
In [9]: sel.xpath("//span[@class='link_title']/a/@href").extract()
Out[9]:
[u'/php_fly/article/details/19364913',
u'/php_fly/article/details/18155421',
u'/php_fly/article/details/17629021',
u'/php_fly/article/details/17619689',
u'/php_fly/article/details/17386163',
u'/php_fly/article/details/17266889',
u'/php_fly/article/details/17172381',
u'/php_fly/article/details/17171985',
u'/php_fly/article/details/17145295',
u'/php_fly/article/details/17122961',
u'/php_fly/article/details/17117891',
u'/php_fly/article/details/14533681',
u'/php_fly/article/details/13162011',
u'/php_fly/article/details/12658277',
u'/php_fly/article/details/12528391',
u'/php_fly/article/details/12421473',
u'/php_fly/article/details/12319943',
u'/php_fly/article/details/12293587',
u'/php_fly/article/details/12293381',
u'/php_fly/article/details/12289803']
修改scrapy shell的请求方式:

[python] view plain
>>> request = request.replace(method="POST")
>>> fetch(request)
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x1e16b50>
...

从Spider中调用Scrapy shell
在爬虫运行过程中,有时需要检查某个响应是否是你所期望的。
这个需求可以通过scrapy.shell.inspect_response函数进行实现
以下是一个关于如何从spider中调用scrapy shell的例子

[python] view plain
from scrapy.spider import Spider

class MySpider(Spider):
name = "myspider"
start_urls = [
"http://example.com",
"http://example.org",
"http://example.net",
]

def parse(self, response):
# We want to inspect one specific response.
if ".org" in response.url:
from scrapy.shell import inspect_response
inspect_response(response)

# Rest of parsing code.
当你启动爬虫的时候,控制台将打印出类似如下的信息
[python] view plain
2014-02-20 17:48:31-0400 [myspider] DEBUG: Crawled (200) <GET http://example.com> (referer: None)
2014-02-20 17:48:31-0400 [myspider] DEBUG: Crawled (200) <GET http://example.org> (referer: None)
[s] Available Scrapy objects:
[s] crawler <scrapy.crawler.Crawler object at 0x1e16b50>
...
>>> response.url
'http://example.org'
注意:当Scrapy engine被scrapy shell占用的时候,Scrapy shell中的fetch函数是无法使用的。 然而,当你退出Scrapy shell的时候,蜘蛛将从停止的地方继续爬行

‘玖’ python shell中怎么重复执行命令

有三种方法:
1、os.system

import os

i = 0

while True:

i = i + 1

os.system("tcpreplay -ibond0 -M 5 -l 1
oracle_request_response.cap")

print"+++++++++++++++++++++++++++++++"

print"times:" ,i

time.sleep(5)

2、os.popen

import os

i = 0

while True:

i = i + 1

print os.popen("tcpreplay -ibond0 -M 5 -l 1
oracle_request_response.cap").read()

print"+++++++++++++++++++++++++++++++"

print"times:" ,i

time.sleep(60)

3、output = Popen("xxx",shell
= True).communicate()[0]

import os

from subprocess import *

i = 0

while True:

i = i + 1

output = Popen("tcpreplay -ibond0 -M 5 -l 1
oracle/*",shell = True).communicate()[0]

print"+++++++++++++++++++++++++++++++"

print"times:" ,i

time.sleep(60)

‘拾’ 请教python如何执行shell管道命令

Python执行Linux系统命令,即在Python脚本中调用Shell命令,具体有以下四种方法:
1、os.system
//仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息
system(command) -> exit_status
Execute the command (a string) in a subshell.
//如果再命令行下执行,结果直接打印出来:
>>> os.system('ls')
04101419778.CHM bash document media py-django video
11.wmv books downloads Pictures python
all-20061022 Desktop Examples project tools
2、os.popen
//该方法不但执行命令还返回执行后的信息对象
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
3、使用模块 subprocess
>>> import subprocess
>>> subprocess.call(["cmd", "arg1", "arg2"],shell=True)
//获取返回和输出:
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
4、使用模块 commands

>>> import commands
>>> dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']
>>> commands.getoutput("date")
'Wed Jun 10 19:39:57 CST 2009'
>>>
>>> commands.getstatusoutput("date")
(0, 'Wed Jun 10 19:40:41 CST 2009')

阅读全文

与python执行shell命令相关的资料

热点内容
android平滑滚动效果 浏览:841
什么是编译器指令 浏览:219
微控制器逻辑命令使用什么总线 浏览:885
程序员在学校里是学什么的 浏览:601
oraclejava数据类型 浏览:890
程序员考注册会计师 浏览:957
怎么使用access的命令按钮 浏览:899
有点钱app在哪里下载 浏览:832
博途v15解压后无法安装 浏览:205
什么是根服务器主机 浏览:438
安卓手游怎么申请退款 浏览:555
安卓系统如何分享网页 浏览:278
ad如何编译pcb工程 浏览:414
除了滴滴app哪里还能用滴滴 浏览:399
截图怎么保存文件夹然后压缩 浏览:8
幻影服务器怎么样 浏览:28
具体哪些广东公司招程序员 浏览:871
嵌入式编译器教程 浏览:307
ssl数据加密传输 浏览:87
51单片机定时器方式2 浏览:332