打印输出ls -l | awk的东西

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

我想在python脚本中获取命令的输出。该命令非常简单 - ls -l $filename | awk '{print $5}',基本上捕获文件的大小

我尝试了几种方法,但我不知道如何正确传递变量文件名。

这两种方法我做错了什么?

谢谢您的帮助

尝试了两种不同的方法如下:

方法1

name = subprocess.check_output("ls -l filename | awk '{print $5}'", shell=True)
print name

在这里ls抱怨文件名不存在,我完全理解,但我不知道如何将文件名作为变量传递

方法2

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-3.x subprocess
1个回答
2
投票

内置的Python模块os可以为您提供特定文件的大小。

以下是与以下方法相关的文档。

os.stat - reference

os.path.getsize - reference

以下是使用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模块。

希望这三种方法中的一种有助于解决您的问题。

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