python使用bash命令的简单介绍

本文目录一览:

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(‘\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’))

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/304724.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2025-01-01 11:05
下一篇 2025-01-01 11:06

相关推荐

  • Python周杰伦代码用法介绍

    本文将从多个方面对Python周杰伦代码进行详细的阐述。 一、代码介绍 from urllib.request import urlopen from bs4 import Bea…

    编程 2025-04-29
  • Python计算阳历日期对应周几

    本文介绍如何通过Python计算任意阳历日期对应周几。 一、获取日期 获取日期可以通过Python内置的模块datetime实现,示例代码如下: from datetime imp…

    编程 2025-04-29
  • Python中引入上一级目录中函数

    Python中经常需要调用其他文件夹中的模块或函数,其中一个常见的操作是引入上一级目录中的函数。在此,我们将从多个角度详细解释如何在Python中引入上一级目录的函数。 一、加入环…

    编程 2025-04-29
  • Python列表中负数的个数

    Python列表是一个有序的集合,可以存储多个不同类型的元素。而负数是指小于0的整数。在Python列表中,我们想要找到负数的个数,可以通过以下几个方面进行实现。 一、使用循环遍历…

    编程 2025-04-29
  • 如何查看Anaconda中Python路径

    对Anaconda中Python路径即conda环境的查看进行详细的阐述。 一、使用命令行查看 1、在Windows系统中,可以使用命令提示符(cmd)或者Anaconda Pro…

    编程 2025-04-29
  • 蝴蝶优化算法Python版

    蝴蝶优化算法是一种基于仿生学的优化算法,模仿自然界中的蝴蝶进行搜索。它可以应用于多个领域的优化问题,包括数学优化、工程问题、机器学习等。本文将从多个方面对蝴蝶优化算法Python版…

    编程 2025-04-29
  • Python清华镜像下载

    Python清华镜像是一个高质量的Python开发资源镜像站,提供了Python及其相关的开发工具、框架和文档的下载服务。本文将从以下几个方面对Python清华镜像下载进行详细的阐…

    编程 2025-04-29
  • python强行终止程序快捷键

    本文将从多个方面对python强行终止程序快捷键进行详细阐述,并提供相应代码示例。 一、Ctrl+C快捷键 Ctrl+C快捷键是在终端中经常用来强行终止运行的程序。当你在终端中运行…

    编程 2025-04-29
  • Python程序需要编译才能执行

    Python 被广泛应用于数据分析、人工智能、科学计算等领域,它的灵活性和简单易学的性质使得越来越多的人喜欢使用 Python 进行编程。然而,在 Python 中程序执行的方式不…

    编程 2025-04-29
  • Python字典去重复工具

    使用Python语言编写字典去重复工具,可帮助用户快速去重复。 一、字典去重复工具的需求 在使用Python编写程序时,我们经常需要处理数据文件,其中包含了大量的重复数据。为了方便…

    编程 2025-04-29

发表回复

登录后才能评论