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/zh-hk/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

發表回復

登錄後才能評論