代碼如下:
output = os.popen('cat /proc/cpuinfo')
print output.read()
通過 os.popen() 返回的是 file read 的對象,對其進行讀取 read() 的操作可以看到執行的輸出。但是無法讀取程序執行的返回值)
嘗試第三種方案 commands.getstatusoutput() 一個方法就可以獲得到返回值和輸出,非常好用。
❷ 怎麼樣在shell腳本中調用python腳本
1、os.system(cmd)
缺點:不能獲取返回值
2、os.popen(cmd)
要得到命令的輸出內容,只需再調用下read()或readlines()等
例:a=os.popen(cmd).read()
3、commands模塊,其實也是對popen的封裝。
此模塊主要有如下方法:
commands.getstatusoutput(cmd)返回(status, output).
commands.getoutput(cmd)只返回輸出結果
commands.getstatus(file)返回ls -ld file的執行結果字元串,調用了getoutput
例:
>>> 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-x1 root13352 Oct 141994 /bin/ls'
來源:麥子學院
❸ python怎麼執行shell命令
工具/原料
Python環境
方法/步驟
os.system("The command you want"). 這個調用相當直接,且是同步進行的,程序需要阻塞並等待返回。返回值是依賴於系統的,直接返回系統的調用返回值,所以windows和linux是不一樣的
os.popen(command[,mode[,bufsize]]),
圖中是一個例子.
可以看出,popen方法通過p.read()獲取終端輸出,而且popen需要關閉close().當執行成功時,close()不返回任何值,失敗
時,close()返回系統返回值. 可見它獲取返回值的方式和os.system不同。
使用commands模塊,圖中是一組例子。根據你需要的不同,commands模塊有三個方法可供選擇。getstatusoutput, getoutput, getstatus。
但是,如上三個方法都不是Python推薦的方法,而且在Python3中其中兩個已經消失。Python文檔中目前全力推薦第四個方法,subprocess! subprocess使用起來同樣簡單:
直
接調用命令,返回值即是系統返回。shell=True表示命令最終在shell中運行。Python文檔中出於安全考慮,不建議使用
shell=True。建議使用Python庫來代替shell命令,或使用pipe的一些功能做一些轉義。官方的出發點是好的,不過真心麻煩了很多,
so.... 如果你更關注命令的終端輸出,可以如下圖這樣操作, 同樣很簡單.
❹ python調用shell腳本 獲取shell腳本中間的輸出值
import os
ss=os.popen("sh test.sh").readlines()
print ss
❺ python 通過subprocess.run調用ubuntu shell腳本 返回值為0卻不列印輸出
應該用格式化串傳進去
'/home/.../test.sh %s' % v
❻ 我在shell里調用一個PYTHON腳本,怎麼拿到這個PYTHON腳本的錯誤輸出
執行如下shell命令:
$ python my.py > out.txt 2> err.txt
則err.txt中會存有執行腳本my.py的錯誤輸出,out.txt中會含有正常的print結果。
❼ 請教在shell中調用python並獲取py返回值的問題
調用並且傳入參數就不必說了吧,很簡單直接python <file_name>.py <arg1> <arg2>
首先,你知道PYTHON是買有main函數的,要想讀到PYTHON裡面RETURN的值恐怕辦不到PYTHON裡面也沒有類似的通道。
但是,你卻可以讀到PYTHON的sterr的error code。PYTHON裡面有個sys模塊,你可以用sys.exit(<num>)的方式,通過把錯誤碼發送給stderr。然後再Shell裡面用$?(事實上$?命令會從stderr裡面去讀) 來判斷python是否執行成功
❽ 如何使用python腳本調用adb shell裡面的命令
python調用Shell腳本,有兩種方法:os.system(cmd)或os.popen(cmd),前者返回值是腳本的退出狀態碼,後者的返回值是腳本執行過程中的輸出內容。實際使用時視需求情況而選擇。
現假定有一個shell腳本
test.sh:
#!/bin/bash
echo "hello world!"
exit 3
❾ 參數傳遞:shell腳本調用一個帶參數的python函數
把a b c寫到文件里,如example.txt,然後shell里:cif filename <example.txt
❿ shell腳本中怎麼調用python腳本中的帶參函數
Python 可以利用 sys.argv 拿到命令列上的 arguments:
$ python test.py 1 2 3
test.py:
import sys
print(sys.argv)
結果:
['test.py', '1', '2', '3']
所以你在 build_using_xctool.sh 中可以這樣調度 python:
python /Users/gyd/Desktop/auto_send_email.py subject msg toaddrs fromaddr smtpaddr password
然後在 auto_send_email.py 中:
import sys # 自己 import sys...if __name__ == '__main__':
sendmail(*sys.argv[1:])