stackoverflow community!
I use python3 to collect some information from a server, but I had this Error and I did not find a solution for it.
This is my code below :
from subprocess import check_output
disks = check_output(("df")).decode("utf-8").split('\n')
print(disks)
and this is the output:
df: /run/user/1001/doc: Operation not permitted
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python3.9/subprocess.py", line 424, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.9/subprocess.py", line 528, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command 'df' returned non-zero exit status 1.
check_output() it work with other commands for example: check_output(("uname")).decode("utf-8") the output is: Linux
Why it work with other commands, but it don't work with df command? and what is the solution for this problem?
the command df it work when I run it from the terminal
CodePudding user response:
Your Python code is fine as such. If you want to avoid the traceback, subprocess.run lets you do that.
from subprocess import run
disks = run(["df"], capture_output=True, text=True)
print(disks.stdout)
The check in check_output means specifically that Python will raise an error if the subprocess fails.
But Python is not doing anything useful here. Simply
import subprocess
subprocess.call(["df"])
would do the same thing with less hassle. (Running df without Python would obviously be more straightforward still.)
CodePudding user response:
It looks like you have a permissions error. You could probably get a better error indication by doing that directly in Python. The following function does the equivalent.
import os
def df(path="/"):
"""Return file system blocks used and free.
Values are same as output of df command.
"""
stat = os.statvfs(path)
return (((stat.f_blocks - stat.f_bfree) * 8),
(stat.f_bavail * (stat.f_frsize // 512)))
