asad128
asad128

Reputation: 95

Check if file path is block device in Python

I have some file path in Python under Linux and I need to figure out if it's a block device - representation of disk or partition. This information is visible when typing ls -l, e.g.

brw-rw---- 1 root disk 8, 1 09-12 18:01 /dev/sda1

I mean letter b on start of this output. Is this possible to get something like this in Python using built in libraries? Eventually I can use subprocess to fetch "ls -l" result and check if first character is correct, but i feel that there could be nicer solution for this. Unfortunately I can't find this. Thanks.

Upvotes: 5

Views: 6076

Answers (2)

nadrimajstor
nadrimajstor

Reputation: 2028

Since 3.4 pathlib offers convenience function Path.is_block_device()

>>> import pathlib
>>> p = pathlib.Path('/dev/vda')
>>> p.is_block_device()
True

Upvotes: 10

Padraic Cunningham
Padraic Cunningham

Reputation: 180512

You can use the stat lib using stat.S_ISBLK with os.stat:

In [1]: import os

In [2]: import stat

In [3]: mode = os.stat("/dev/sda2").st_mode

In [4]: stat.S_ISBLK(mode)
Out[4]: True

In [5]: mode = os.stat("/dev/sr0").st_mode

In [6]: stat.S_ISBLK(mode)
Out[6]: True

Upvotes: 9

Related Questions