Python2.7读取Linux命令dh -h输出遇OSError,求最优读取方法
OSError: [Errno 2] No such file or directory with subprocess.check_output in Python 2.7 Hey there! Let's sort out this issue you're hitting when trying to read the output of df -h (I'm guessing you meant df -h instead of dh -h—that's the standard Linux command for checking disk usage, right?) using Python 2.7's subprocess.check_output.
Why the Error Happens
The root cause here is how check_output handles command arguments in Python 2.7 by default. If you pass a single string like "df -h" without setting shell=True, Python tries to look for an executable file literally named df -h (with the space included) instead of running the df command with the -h flag. That's why you get the "No such file or directory" error.
The Best Ways to Read Linux Command Output
Let's go through the optimal approaches, ordered by best practice:
1. Split the Command Into a List (Recommended, Most Secure)
This is the safest and most efficient method because it avoids spawning a shell, eliminating the risk of shell injection attacks (critical if your command includes user-provided input). Pass the command and its arguments as separate elements in a list:
import subprocess try: # Split command and args into a list raw_output = subprocess.check_output(['df', '-h']) # Convert bytes to string (Python 2.7 returns bytes; strip removes extra newlines) output = raw_output.strip() print(output) except subprocess.CalledProcessError as e: # Handle cases where the command exits with a non-zero code print(f"Command failed with exit code {e.returncode}: {e.output}") except OSError as e: # Handle cases where the command itself isn't found print(f"Could not execute command: {e}")
2. Use shell=True (Only When Necessary)
If your command relies on shell features like pipes (|), wildcards (*), or environment variable expansion, you can use shell=True. But be cautious—never use this with untrusted input, as it can lead to security vulnerabilities:
import subprocess try: # Use shell=True to run the command through the system shell raw_output = subprocess.check_output('df -h', shell=True) output = raw_output.strip() print(output) except subprocess.CalledProcessError as e: print(f"Command failed: {e}") except OSError as e: print(f"Execution error: {e}")
Bonus: Handling Encoding (If Needed)
In Python 2.7, check_output returns a byte string. If you need to work with Unicode, decode it using the appropriate encoding for your system (usually utf-8):
output_str = raw_output.decode('utf-8').strip()
Why the List Method Is Better
- Security: No shell means no risk of malicious input being executed as part of the command.
- Efficiency: Avoids the overhead of spawning a separate shell process.
- Clarity: Explicitly separates the command from its arguments, making your code easier to read and debug.
内容的提问来源于stack exchange,提问作者preethy tulpi

