簡體   English   中英

subprocess.check_output 中的 FileNotFoundError

[英]FileNotFoundError in subprocess.check_output

我想在python環境下連接使用adb的功能。 在終端中, adb 連接良好,如下圖所示。

$ adb --version
Android Debug Bridge version 1.0.41
Version 31.0.3-7562133
Installed as /opt/homebrew/bin/adb

$ command -v adb
/opt/homebrew/bin/adb

為了在 python 環境中使用它,使用了 subprocess.check_output,我編寫了 python 代碼如下。

import subprocess

cmd = f"adb --version"
print(f"cmd:{cmd}")
res = subprocess.check_output(cmd).decode("utf-8")
print(f"res:{res}")

我收到如下錯誤。

$ python test.py
cmd:adb --version
Traceback (most recent call last):
  File "/Users/hhd/project/hhdpy/test.py", line 5, in <module>
    res = subprocess.check_output(cmd).decode("utf-8")
  File "/opt/homebrew/anaconda3/envs/hhdpy/lib/python3.9/subprocess.py", line 424, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/opt/homebrew/anaconda3/envs/hhdpy/lib/python3.9/subprocess.py", line 505, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/opt/homebrew/anaconda3/envs/hhdpy/lib/python3.9/subprocess.py", line 951, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/opt/homebrew/anaconda3/envs/hhdpy/lib/python3.9/subprocess.py", line 1821, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'adb --version'

在我看來,subprocess.check_output 似乎無法導入PATH 環境變量,應該如何解決?

正如 John 所建議的,一種可能的解決方案是提供--version作為參數。

為此,您必須將cmd命令拆分為一個列表,例如:

res = subprocess.check_output(["adb", "--version"]).decode("utf-8")

用 Python3 測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM