Reputation: 89
I want to get the output of command in a python script. The command is pretty straightforward - ls -l $filename | awk '{print $5}'
, essentially capture the size of a file
I have tried a couple of ways but I somehow can't get the variable filename passed in correctly.
What am I doing wrong with either approach?
Thanks for the help
Have tried two different ways as below:
name = subprocess.check_output("ls -l filename | awk '{print $5}'", shell=True)
print name
Here ls
complains that filename does not exist which I totally understand, but I am not sure what I would do to pass filename as a variable
first = ['ls', '-l', filename]
second = ['awk', ' /^default/ {print $5}']
p1 = subprocess.Popen(first, stdout=subprocess.PIPE)
p2 = subprocess.Popen(second, stdin=p1.stdout, stdout=subprocess.PIPE)
out = p2.stdout.read()
print out
Here it just prints nothing.
actual result would be the size of the file.
Upvotes: 1
Views: 920
Reputation: 15629
The builtin Python module os
can provide you the size of a specific file.
Here is the documentation related to the methods below.
Here are two methods using the Python module os
to obtain the filesize:
import os
# Use os.stat with st_size
filesize_01 = os.stat('filename.txt').st_size
print (filesize_01)
# outputs
30443963
# os.path.getsize(path) Return the size, in bytes, of path.
filesize_02 = os.path.getsize('filename.txt')
print (filesize_02)
# outputs
30443963
I'm adding this subprocess
example, because of the conversations concerning the use of os
on this question. I decided to use the stat
command over the ls
command. I'm also using subprocess.check_output
instead of subprocess.Popen
, which was used in your question. The example below can be added to a try block with error handling.
subprocess.check_output - reference
from subprocess import check_output
def get_file_size(filename):
# stat command
# -f display information using the specified format
# the %z format selects the size in bytes
output = check_output(['stat', '-f', '%z', str({}).format(filename)])
# I also use the f-string in this print statement.
# ref: https://realpython.com/python-f-strings/
print(f"Filesize of {filename} is: {output.decode('ASCII')}")
# outputs
30443963
get_file_size('filename.txt')
My personal preference is the os
module, but yours might be the subprocess
module.
Hopefully, one of these three methods will help solve your question.
Upvotes: 3