我想在python脚本中获取命令的输出。该命令非常简单 - ls -l $filename | awk '{print $5}'
,基本上捕获文件的大小
我尝试了几种方法,但我不知道如何正确传递变量文件名。
这两种方法我做错了什么?
谢谢您的帮助
尝试了两种不同的方法如下:
name = subprocess.check_output("ls -l filename | awk '{print $5}'", shell=True)
print name
在这里ls
抱怨文件名不存在,我完全理解,但我不知道如何将文件名作为变量传递
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
这里它什么都不打印。
实际结果将是文件的大小。
内置的Python模块os
可以为您提供特定文件的大小。
以下是与以下方法相关的文档。
以下是使用Python模块os
获取文件大小的两种方法:
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
我正在添加这个subprocess
示例,因为关于在这个问题上使用os
的对话。我决定在stat
命令中使用ls
命令。我也使用subprocess.check_output
而不是subprocess.Popen
,这是在你的问题中使用的。可以将以下示例添加到具有错误处理的try块中。
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')
我个人的偏好是os
模块,但你的可能是subprocess
模块。
希望这三种方法中的一种有助于解决您的问题。