Python을 사용하여 볼륨에 남아있는 교차 플랫폼 공간
Linux, Windows 및 OS X에서 Python을 사용하여 디스크 볼륨에 남아있는 공간을 확인하는 방법이 필요합니다. 현재이 작업을 수행하기 위해 다양한 시스템 호출 (df, dir)의 출력을 구문 분석하고 있습니다. 더 좋은 방법이 있습니까?
import ctypes
import os
import platform
import sys
def get_free_space_mb(dirname):
"""Return folder/drive free space (in megabytes)."""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024 / 1024
이 점에 유의 해야한다 에 대한 디렉토리 이름을 전달 GetDiskFreeSpaceEx()
작업으로는 ( statvfs()
파일과 디렉토리의 양쪽 모두에서 작동). .NET을 사용하여 파일에서 디렉토리 이름을 가져올 수 있습니다 os.path.dirname()
.
os.statvfs()
및에 대한 설명서도 참조하십시오 GetDiskFreeSpaceEx
.
를 사용하여 psutil 을 설치합니다 pip install psutil
. 그런 다음 다음을 사용하여 여유 공간을 바이트 단위로 얻을 수 있습니다.
import psutil
print(psutil.disk_usage(".").free)
Windows 에는 wmi 모듈을, unix에는 os.statvfs를 사용할 수 있습니다.
창용
import wmi
c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
print( d.Caption, d.FreeSpace, d.Size, d.DriveType)
유닉스 또는 리눅스 용
from os import statvfs
statvfs(path)
python3을 실행하는 경우 :
이름 정규화 작업 shutil.disk_usage()
과 함께 사용 os.path.realpath('/')
:
from os import path
from shutil import disk_usage
print([i / 1000000 for i in disk_usage(path.realpath('/'))])
또는
total_bytes, used_bytes, free_bytes = disk_usage(path.realpath('D:\\Users\\phannypack'))
print(total_bytes / 1000000) # for Mb
print(used_bytes / 1000000)
print(free_bytes / 1000000)
총, 사용 및 여유 공간 (MB)을 제공합니다.
다른 종속성을 추가하고 싶지 않다면 Windows에서 ctypes를 사용하여 win32 함수 호출을 직접 호출 할 수 있습니다.
import ctypes
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\\'), None, None, ctypes.pointer(free_bytes))
if free_bytes.value == 0:
print 'dont panic'
좋은 크로스 플랫폼 방법은 psutil : http://pythonhosted.org/psutil/#disks를 사용 하는 것입니다 (psutil 0.3.0 이상이 필요합니다).
Python 3.3에서는 Windows 및 UNIX 용 표준 라이브러리에서 shutil.disk_usage ( "/"). free 를 사용할 수 있습니다 . :)
You can use df as a cross-platform way. It is a part of GNU core utilities. These are the core utilities which are expected to exist on every operating system. However, they are not installed on Windows by default (Here, GetGnuWin32 comes in handy).
df is a command-line utility, therefore a wrapper required for scripting purposes. For example:
from subprocess import PIPE, Popen
def free_volume(filename):
"""Find amount of disk space available to the current user (in bytes)
on the file system containing filename."""
stats = Popen(["df", "-Pk", filename], stdout=PIPE).communicate()[0]
return int(stats.splitlines()[1].split()[3]) * 1024
The os.statvfs() function is a better way to get that information for Unix-like platforms (including OS X). The Python documentation says "Availability: Unix" but it's worth checking whether it works on Windows too in your build of Python (ie. the docs might not be up to date).
Otherwise, you can use the pywin32 library to directly call the GetDiskFreeSpaceEx function.
Below code returns correct value on windows
import win32file
def get_free_space(dirname):
secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)
return secsPerClus * bytesPerSec * nFreeClus
I Don't know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each.
For Windows, there's the GetDiskFreeSpaceEx method in the win32 extensions.
참고URL : https://stackoverflow.com/questions/51658/cross-platform-space-remaining-on-volume-using-python
'IT박스' 카테고리의 다른 글
MySQL : 최신 기록 가져 오기 (0) | 2020.11.04 |
---|---|
널 포인터가 모든 비트가 0이 아닐 때 C / C ++ 코드를 올바르게 작성하는 방법 (0) | 2020.11.04 |
하드웨어 설명 언어 (Verilog, VHDL 등)에 대한 모범 사례는 무엇입니까? (0) | 2020.11.04 |
자바 스크립트; (0) | 2020.11.04 |
상속 된 클래스가 아닌 클래스의 리플렉션 속성으로 가져옵니다. (0) | 2020.11.04 |