Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 943
asad128 Avatar asked Dec 11 '22 21:12

asad128


1 Answers

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
like image 145
Padraic Cunningham Avatar answered Jan 16 '23 17:01

Padraic Cunningham