使用subprocess.check_output()打印Ifconfig会出错

问题描述 投票:0回答:1

文件名是Main.py

import subprocess

Interface = "eth0"
output1 = subprocess.check_output(["ifconfig", Interface])

当我尝试执行以上命令时,出现以下错误。

/kunal/PycharmProjects/first/venv/bin/python /kunal/PycharmProjects/first/main.py
Traceback (most recent call last):
  File "/kunal/PycharmProjects/first/main.py", line 4, in <module>
    output1 = subprocess.check_output(["ifconfig", Interface])
  File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.8/subprocess.py", line 489, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ifconfig'

Process finished with exit code 1

运行程序时环境的相关部分是:

HOME: /kunal
PATH: /kunal/PycharmProjects/first/venv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
PS1: (venv) 
PWD: /kunal/PycharmProjects/first
PYCHARM_HOSTED: 1
PYTHONIOENCODING: UTF-8
PYTHONPATH: /kunal/PycharmProjects/first
PYTHONUNBUFFERED: 1
SHELL: /bin/bash
USER: kunal
VIRTUAL_ENV: /kunal/PycharmProjects/first/venv

shell上的'env'路径是:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

“ ifconfig的结果:

/usr/sbin/ifconfig
python python-3.x subprocess
1个回答
0
投票

$PATH变量中不存在路径。

nano /etc/bash.bashrc

添加Export PATH=$PATH:/usr/sbin作为ifconfig之类的命令。

© www.soinside.com 2019 - 2024. All rights reserved.