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命令)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codeforces Round #36
- 下一篇: Python:每日一题001