日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python subprocess.check_output 执行shell命令 返回结果(单次执行shell命令)

發布時間:2025/3/15 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python subprocess.check_output 执行shell命令 返回结果(单次执行shell命令) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python3中的subprocess.check_output函數可以執行一條sh命令,并返回命令的輸出內容,用法如下:

output = subprocess.check_output(["python3", "xx.py"], shell = False)

該函數兩個參數第一個表示命令內容,因為中間有空格所以用中括號這種形式,同時制定shell=False表示命令分開寫了。而該命令執行后的輸出內容會返回給output變量。

需要注意的是這個output變量并不是一個string,也就是說不能用string的一些函數,比如你想知道返回的輸出中是否包含某個字符串:

output = subprocess.check_output(["python3", "xx.py"], shell = False) if (output.find("yes") >= 0): print("yes") else: print("no")

這樣執行后不會有任何輸出,因為find()函數是給string用的,而這里的output其實不是一個string,那它是個什么呢?

我們看看python3的subprocess.check_output的文檔:

By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

也就是說,返回的其實是一個編碼后的比特值,實際的編碼格式取決于調用的命令,因此python3將解碼過程交給應用層,也就是我們使用的人來做。

這樣就清晰了,要對輸出使用stirng的操作,需要先通過解碼將其轉換成string:

output = subprocess.check_output(["python3", "xx.py"], shell = False) out = output.decode() if (out.find("yes") >= 0): print("yes") else: print("no")

這樣就可以正常判斷了。

總結

以上是生活随笔為你收集整理的Python subprocess.check_output 执行shell命令 返回结果(单次执行shell命令)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。