【问题标题】:FileNotFoundError in subprocess.check_outputsubprocess.check_output 中的 FileNotFoundError
【发布时间】:2022-01-15 15:03:30
【问题描述】:

我想在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环境变量, 我该如何解决?

【问题讨论】:

  • 它将--version 视为文字命令名称的一部分。大概您的意思是命令只是adbargument--version
  • @Hyundong Hwang 下面的答案是否有助于解决问题?

标签: python subprocess adb


【解决方案1】:

正如 John 所建议的,一种可能的解决方案是提供 --version 作为参数。

为此,您必须将cmd 命令拆分为一个列表,例如:

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

用 Python3 测试。

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 2021-06-27
    • 2020-12-05
    • 1970-01-01
    • 2021-12-29
    • 2015-10-19
    • 1970-01-01
    • 2015-05-04
    • 2014-06-18
    相关资源
    最近更新 更多