欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python調(diào)用shell命令常用方法(4種)

 更新時(shí)間:2020年05月11日 11:18:42   作者:*陌上花開(kāi)*  
這篇文章主要介紹了Python調(diào)用shell命令常用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

方法一、使用os模塊的system方法:os.system(cmd),其返回值是shell指令運(yùn)行后返回的狀態(tài)碼,int類型,0表示shell指令成功執(zhí)行,256表示未找到,該方法適用于shell命令不需要輸出內(nèi)容的場(chǎng)景。

舉例說(shuō)明:

1. 列舉當(dāng)前目錄下的所有文件。

import os
val = os.system('ls -al')
print val

沒(méi)有找到時(shí),sh返回的狀態(tài)碼是1,而適用python調(diào)用,返回的是:256

方法二、使用os.popen(),該方法以文件的形式返回shell指令運(yùn)行后的結(jié)果,需要獲取內(nèi)容時(shí)可使用read()或readlines()方法,舉例如下:

方法三、使用commands模塊,有三個(gè)方法可以使用:

(1)commands.getstatusoutput(cmd),其以字符串的形式返回的是輸出結(jié)果和狀態(tài)碼,即(status,output)。

(2)commands.getoutput(cmd),返回cmd的輸出結(jié)果。

(3)commands.getstatus(file),返回ls -l file的執(zhí)行結(jié)果字符串,調(diào)用了getoutput,不建議使用此方法

方法四、subprocess模塊,允許創(chuàng)建很多子進(jìn)程,創(chuàng)建的時(shí)候能指定子進(jìn)程和子進(jìn)程的輸入、輸出、錯(cuò)誤輸出管道,執(zhí)行后能獲取輸出結(jié)果和執(zhí)行狀態(tài)。

(1)subprocess.run():python3.5中新增的函數(shù), 執(zhí)行指定的命令, 等待命令執(zhí)行完成后返回一個(gè)包含執(zhí)行結(jié)果的CompletedProcess類的實(shí)例。

(2)subprocess.call():執(zhí)行指定的命令, 返回命令執(zhí)行狀態(tài), 功能類似os.system(cmd)。

(3)subprocess.check_call():python2.5中新增的函數(shù), 執(zhí)行指定的命令, 如果執(zhí)行成功則返回狀態(tài)碼, 否則拋出異常。

說(shuō)明:subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)

   subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

   subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

   args:表示shell指令,若以字符串形式給出shell指令,如"ls -l "則需要使shell = Ture。否則默認(rèn)已數(shù)組形式表示shell變量,如"ls","-l"。

   當(dāng)使用比較復(fù)雜的shell語(yǔ)句時(shí),可以先使用shlex模塊的shlex.split()方法來(lái)幫助格式化命令,然后在傳遞給run()方法或Popen。

附上python2.7中的subprocess模塊源碼供理解(pycharm查看方法源碼,ctrl+左鍵)。

# Stubs for subprocess

# Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub

from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text

_FILE = Union[None, int, IO[Any]]
_TXT = Union[bytes, Text]
_CMD = Union[_TXT, Sequence[_TXT]]
_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]]

# Same args as Popen.__init__
def call(args: _CMD,
     bufsize: int = ...,
     executable: _TXT = ...,
     stdin: _FILE = ...,
     stdout: _FILE = ...,
     stderr: _FILE = ...,
     preexec_fn: Callable[[], Any] = ...,
     close_fds: bool = ...,
     shell: bool = ...,
     cwd: _TXT = ...,
     env: _ENV = ...,
     universal_newlines: bool = ...,
     startupinfo: Any = ...,
     creationflags: int = ...) -> int: ...

def check_call(args: _CMD,
        bufsize: int = ...,
        executable: _TXT = ...,
        stdin: _FILE = ...,
        stdout: _FILE = ...,
        stderr: _FILE = ...,
        preexec_fn: Callable[[], Any] = ...,
        close_fds: bool = ...,
        shell: bool = ...,
        cwd: _TXT = ...,
        env: _ENV = ...,
        universal_newlines: bool = ...,
        startupinfo: Any = ...,
        creationflags: int = ...) -> int: ...

# Same args as Popen.__init__ except for stdout
def check_output(args: _CMD,
         bufsize: int = ...,
         executable: _TXT = ...,
         stdin: _FILE = ...,
         stderr: _FILE = ...,
         preexec_fn: Callable[[], Any] = ...,
         close_fds: bool = ...,
         shell: bool = ...,
         cwd: _TXT = ...,
         env: _ENV = ...,
         universal_newlines: bool = ...,
         startupinfo: Any = ...,
         creationflags: int = ...) -> bytes: ...

PIPE = ... # type: int
STDOUT = ... # type: int

class CalledProcessError(Exception):
  returncode = 0
  # morally: _CMD
  cmd = ... # type: Any
  # morally: Optional[bytes]
  output = ... # type: Any

  def __init__(self,
         returncode: int,
         cmd: _CMD,
         output: Optional[bytes] = ...) -> None: ...

class Popen:
  stdin = ... # type: Optional[IO[Any]]
  stdout = ... # type: Optional[IO[Any]]
  stderr = ... # type: Optional[IO[Any]]
  pid = 0
  returncode = 0

  def __init__(self,
         args: _CMD,
         bufsize: int = ...,
         executable: Optional[_TXT] = ...,
         stdin: Optional[_FILE] = ...,
         stdout: Optional[_FILE] = ...,
         stderr: Optional[_FILE] = ...,
         preexec_fn: Optional[Callable[[], Any]] = ...,
         close_fds: bool = ...,
         shell: bool = ...,
         cwd: Optional[_TXT] = ...,
         env: Optional[_ENV] = ...,
         universal_newlines: bool = ...,
         startupinfo: Optional[Any] = ...,
         creationflags: int = ...) -> None: ...

  def poll(self) -> int: ...
  def wait(self) -> int: ...
  # morally: -> Tuple[Optional[bytes], Optional[bytes]]
  def communicate(self, input: Optional[_TXT] = ...) -> Tuple[Any, Any]: ...
  def send_signal(self, signal: int) -> None: ...
  def terminate(self) -> None: ...
  def kill(self) -> None: ...
  def __enter__(self) -> 'Popen': ...
  def __exit__(self, type, value, traceback) -> bool: ...

# Windows-only: STARTUPINFO etc.

STD_INPUT_HANDLE = ... # type: Any
STD_OUTPUT_HANDLE = ... # type: Any
STD_ERROR_HANDLE = ... # type: Any
SW_HIDE = ... # type: Any
STARTF_USESTDHANDLES = ... # type: Any
STARTF_USESHOWWINDOW = ... # type: Any
CREATE_NEW_CONSOLE = ... # type: Any
CREATE_NEW_PROCESS_GROUP = ... # type: Any

shell腳本使用python腳本的參數(shù)

寫(xiě)一個(gè)hello.sh腳本,需要傳入兩個(gè)參數(shù):

執(zhí)行結(jié)果如下:

在python腳本中調(diào)用shell腳本,并傳入?yún)?shù),注意參數(shù)前后要有空格

執(zhí)行python腳本

到此這篇關(guān)于Python調(diào)用shell命令常用方法(4種)的文章就介紹到這了,更多相關(guān)Python調(diào)用shell命令內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python NumPy中的隨機(jī)數(shù)及ufuncs函數(shù)使用示例詳解

    Python NumPy中的隨機(jī)數(shù)及ufuncs函數(shù)使用示例詳解

    這篇文章主要介紹了Python NumPy中的隨機(jī)數(shù)及ufuncs函數(shù)使用,ufunc函數(shù)是NumPy中的一種通用函數(shù),它可以對(duì)數(shù)組中的每個(gè)元素進(jìn)行操作,而不需要使用循環(huán)語(yǔ)句,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧
    2023-05-05
  • 深入詳解Python中dotted庫(kù)的使用

    深入詳解Python中dotted庫(kù)的使用

    Python的dotted庫(kù)提供了一種便捷的方式來(lái)處理嵌套字典和列表,允許通過(guò)點(diǎn)分隔的路徑字符串來(lái)訪問(wèn)和設(shè)置嵌套結(jié)構(gòu)中的數(shù)據(jù),下面我們就來(lái)看看它的具體使用
    2019-04-04
  • Python開(kāi)發(fā)畢設(shè)案例之桌面學(xué)生信息管理程序

    Python開(kāi)發(fā)畢設(shè)案例之桌面學(xué)生信息管理程序

    畢業(yè)設(shè)計(jì)必備案例:Python開(kāi)發(fā)桌面程序
    2021-11-11
  • Python實(shí)現(xiàn)的二維碼生成小軟件

    Python實(shí)現(xiàn)的二維碼生成小軟件

    這篇文章主要介紹了Python實(shí)現(xiàn)的二維碼生成小軟件,使用wxPython、python-qrcode、pyqrcode、pyqrnative等技術(shù)和開(kāi)源類庫(kù)實(shí)現(xiàn),需要的朋友可以參考下
    2014-07-07
  • python過(guò)濾中英文標(biāo)點(diǎn)符號(hào)的實(shí)例代碼

    python過(guò)濾中英文標(biāo)點(diǎn)符號(hào)的實(shí)例代碼

    今天小編就為大家分享一篇python過(guò)濾中英文標(biāo)點(diǎn)符號(hào)的實(shí)例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-07-07
  • python中的項(xiàng)目目錄結(jié)構(gòu)

    python中的項(xiàng)目目錄結(jié)構(gòu)

    這篇文章主要介紹了python中的項(xiàng)目目錄結(jié)構(gòu),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • pytorch 改變tensor尺寸的實(shí)現(xiàn)

    pytorch 改變tensor尺寸的實(shí)現(xiàn)

    今天小編就為大家分享一篇pytorch 改變tensor尺寸的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-01-01
  • python刪除特定文件的方法

    python刪除特定文件的方法

    這篇文章主要介紹了python刪除特定文件的方法,涉及Python文件查找及刪除的相關(guān)技巧,需要的朋友可以參考下
    2015-07-07
  • flask與數(shù)據(jù)庫(kù)的交互操作示例

    flask與數(shù)據(jù)庫(kù)的交互操作示例

    這篇文章主要為大家介紹了flask與數(shù)據(jù)庫(kù)的交互操作示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • 使用python爬取抖音app視頻的實(shí)例代碼

    使用python爬取抖音app視頻的實(shí)例代碼

    這篇文章主要介紹了使用python爬取抖音app視頻的實(shí)例代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12

最新評(píng)論