溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python執(zhí)行外部命令的方法

發(fā)布時(shí)間:2020-08-06 13:57:52 來源:億速云 閱讀:171 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)Python執(zhí)行外部命令的方法的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過來看看吧。

調(diào)用shell命令

#!/usr/bin/python3

import subprocess

# 執(zhí)行外部命令 'date'
subprocess.call('date')

# 傳遞選項(xiàng)和參數(shù)給命令
print("\nToday is ", end="", flush=True)
subprocess.call(['date', '-u', '+%A'])

# 其他例子
print("\nSearching for 'hello world'", flush=True)
subprocess.call(['grep', '-i', 'hello world', 'hello_world.py'])

這里的import語句用于載入subprocess模塊,它是Python標(biāo)準(zhǔn)庫的一部分

subprocess模塊中的call函數(shù)是一種執(zhí)行外部命令的方式

通過傳遞True給flush參數(shù)(默認(rèn)是False),我們確保這個(gè)信息在subprocess.call運(yùn)行之前輸出

想要給命令傳遞參數(shù),需要使用字符串列表

$ ./calling_shell_commands.py
Tue Jun 21 18:35:33 IST 2016

Today is Tuesday

Searching for 'hello world'
print("Hello World")

使用擴(kuò)展調(diào)用shell命令

#!/usr/bin/python3

import subprocess

# 不使用擴(kuò)展調(diào)用Shell命令
print("No shell expansion when shell=False", flush=True)
subprocess.call(['echo', 'Hello $USER'])

# 使用Shell擴(kuò)展調(diào)用Shell命令
print("\nshell expansion when shell=True", flush=True)
subprocess.call('echo Hello $USER', shell=True)

# 如果引號(hào)是命令的一部分則進(jìn)行反義
print("\nSearching for 'hello world'", flush=True)
subprocess.call('grep -i \'hello world\' hello_world.py', shell=True)

默認(rèn)subprocess.call不會(huì)擴(kuò)展shell 通配符,使用 command替換等等

可以設(shè)定shell參數(shù)為True進(jìn)行重寫

注意現(xiàn)在整個(gè)命令行都作為一個(gè)字符串而不是字符串列表

命令中含有引號(hào)如要轉(zhuǎn)義

僅在你確定命令會(huì)正確執(zhí)行的情況下使用shell=True,否則會(huì)存在安全問題

$ ./shell_expansion.py
No shell expansion when shell=False
Hello $USER

shell expansion when shell=True
Hello learnbyexample

Searching for 'hello world'
print("Hello World")

在特定情況下,我們可以使用單/雙引號(hào)的組合來避免使用轉(zhuǎn)義符號(hào)

# 像這樣使用另一種引號(hào)
subprocess.call('grep -i "hello world" hello_world.py', shell=True)

# 或者這樣
subprocess.call("grep -i 'hello world' hello_world.py", shell=True)

Shell命令重定向可以正常使用

# 為了避免call函數(shù)字符串太常,我們使用變量先存儲(chǔ)命令
cmd = "grep -h 'test' report.log test_list.txt > grep_test.txt"
subprocess.call(cmd, shell=True)

避開使用shell=True

>>> import subprocess, os
>>> subprocess.call(['echo', 'Hello', os.environ.get("USER")])
Hello learnbyexample
0

os.environ.get("USER")返回環(huán)境變量USER的值

0退出狀態(tài)碼,意味著成功執(zhí)行了命令。

獲取命令輸出和重定向

#!/usr/bin/python3

import subprocess

# 輸出也包含任何的錯(cuò)誤信息
print("Getting output of 'pwd' command", flush=True)
curr_working_dir = subprocess.getoutput('pwd')
print(curr_working_dir)

# 獲取命令執(zhí)行的狀態(tài)和輸出
# 退出狀態(tài)碼不是“0”意味著有什么事情出錯(cuò)了
ls_command = 'ls hello_world.py xyz.py'
print("\nCalling command '{}'".format(ls_command), flush=True)
(ls_status, ls_output) = subprocess.getstatusoutput(ls_command)
print("status: {}\noutput: '{}'".format(ls_status, ls_output))

# 抑制出錯(cuò)信息
# subprocess.call()返回命令的狀態(tài)碼 returns status of command which can be used instead
print("\nCalling command with error msg suppressed", flush=True)
ls_status = subprocess.call(ls_command, shell=True, stderr=subprocess.DEVNULL)
print("status: {}".format(ls_status))

getstatusoutput()的輸出是元組數(shù)據(jù)類型,更多信息和例子在后續(xù)章節(jié)

getstatusoutput()和getoutput()老式的函數(shù)

使用有更多特性和安全選項(xiàng)的新函數(shù)

$ ./shell_command_output_redirections.py
Getting output of 'pwd' command
/home/learnbyexample/Python/python_programs

Calling command 'ls hello_world.py xyz.py'
status: 2
output: 'ls: cannot access xyz.py: No such file or directory
hello_world.py'

Calling command with error msg suppressed
hello_world.py
status: 2

感謝各位的閱讀!關(guān)于Python執(zhí)行外部命令的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI