首页 > 编程知识 正文

python使用bash命令的简单介绍

时间:2023-12-27 22:27:01 阅读:325300 作者:JMBU

本文目录一览:

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

1

2

3

4

5

6

输出:

leehao.me

process.communicate()方法可以实现主进程与子进程的通信。主进程可以通过它向子进程发送数据,也可以读取子进程的输出的数据。上面的例子中,我们在创建Popen对象时指定stdout=subprocess.PIPE,这样主进程便可以读取子进程的输出。

communicate()方法返回一个元组:(stdoutdata, stderrdata),process.communicate()[0]即获取子进程的标准输出。

需要指出的是,调用communicate()方法后,主进程也会等待子进程执行完毕。

上面的例子中,子进程向标准输出打印两个字符串,主进程接收到了这些输出,并打印出来。

在Python运行bash命令问题,怎么解决

最近有个需求就是页面上执行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如何使用gitbash执行git命令?

代码如下:

#!/usr/bin/env python# -*- coding: utf-8 -*-#

@name   : find_t.py# @author : cat#

@date   : 2017/8/2.import osimport timedef bash_shell(bash_command):

"""

python 中执行 bash 命令     :param bash_command:

:return: bash 命令执行后的控制台输出

"""

try:    

return os.popen(bash_command).read().strip()  

except:        return Nonedef find_target(target_path="./../", key='.git'):

"""

查找目标目录所在的目录 : 如

/aa/bb/.git -- return /aa/bb/

:param target_path:

:param key: target

:return:

"""

walk = os.walk(target_path)  

for super_dir, dir_names, file_names in walk:      

for dir_name in dir_names:          

if dir_name == key:

dir_full_path = os.path.join(super_dir, dir_name)              

# print(dir_full_path, super_dir, dir_name, sep=" ## ")

yield super_dirif __name__ == '__main__':

print("start execute bash ...........")

st = time.time()

cwd = os.getcwd()  

# this for repo

f

or repo_path in find_target(os.getcwd(), key='.repo'):

os.chdir(repo_path)    

if repo_path == os.getcwd():

print('find repo in --', repo_path)

print(bash_shell('pwd'))

print(bash_shell('repo forall -c git config core.fileMode false --replace-all'))      

else:

print('error in chdir 2 {}'.format(repo_path))      

if os.getcwd() != cwd:

os.chdir(cwd)    

if os.getcwd() != cwd:

print('change 2 cwd FAIL !!!  {}'.format(cwd))  

# this for git

for git_path in find_target(os.getcwd(), key='.git'):

os.chdir(git_path)    

if git_path == os.getcwd():

print('find git in --', git_path)

print(bash_shell('pwd'))

print(bash_shell('git config --global core.filemode false'))      

else:

print('error in chdir 2 {}'.format(git_path))      

if os.getcwd() != cwd:

os.chdir(cwd)    

if os.getcwd() != cwd:

print('change 2 cwd FAIL !!!  {}'.format(cwd))

et = time.time()

print('nn  

#### execute finished in {:.3f} seconds ####'.format(et - st))

print('n')    # test for bash_command

# print(bash_shell('git init'))

# print(bash_shell('ls -al'))

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。