打印输出ls -l |有点东西

时间:2019-04-05 23:07:27

标签: python-3.x subprocess

我想在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

这里只打印任何内容。

实际结果将是文件的大小。

1 个答案:

答案 0 :(得分: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模块。

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

相关问题