python使用bash命令的简单介绍

发布时间:2022-11-19

本文目录一览:

  1. python shell怎么使用
  2. 在Python运行bash命令问题,怎么解决
  3. python如何使用gitbash执行git命令?

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"])

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

child = subprocess.Popen("ping -c 5 leehao.me", shell=True)

官方文档指出由于安全原因故不建议使用 shell=True,详细说明可以参考官方文档的描述。

等待子进程执行

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

child = subprocess.Popen(["ping","-c","5","leehao.me"])
child.wait()
print 'parent finish'

这样,主进程会等待子进程执行 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 ')

输出:

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 文档中的一个例子:

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 os
import time
def bash_shell(bash_command):
    """
    python 中执行 bash 命令
    :param bash_command:
    :return: bash 命令执行后的控制台输出
    """
    try:
        return os.popen(bash_command).read().strip()
    except:
        return None
def 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_dir
if __name__ == '__main__':
    print("start execute bash ...........")
    st = time.time()
    cwd = os.getcwd()
    # this for repo
    for 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('\n\n #### execute finished in {:.3f} seconds ####'.format(et - st))
    print('\n')
    # test for bash_command
    # print(bash_shell('git init'))
    # print(bash_shell('ls -al'))