0

Is there a function that I can use to find out if a file is a block device? And another for a character device. I'm trying to create a funtion that will build a string the is exactly like the result you get from running ls -l for a slightly larger program I'm working on. Maybe it would save me some time if that function already existed, what would be helpful as well. Thanks.

3
Contributors
6
Replies
126
Views
3 Years
Discussion Span
Last Post by woooee
0

I get something in my linux system with module pyudev

>>> from pyudev import Context, Device
>>> context = Context()
>>> d = Device.from_device_file(context, '/dev/sda')
>>> d.subsystem
u'block'

Edited by Gribouillis

0

You can also use subprocess to get the results of ls -l. Note the r(epr)

import subprocess
output = subprocess.check_output([r'ls', '-l'])
print output
0

This looks better

import os
import stat
script = __name__ == '__main__'

def is_block_device(filename):
    try:
        mode = os.lstat(filename).st_mode
    except OSError:
        return False
    else:
        return stat.S_ISBLK(mode)

if script:
    print(is_block_device('/dev/sda'))
    print(is_block_device('/home'))
    print(is_block_device('/foo'))

""" my output -->
True
False
False
"""

Edited by Gribouillis

0

Gribouillis where did the parameter mode come from in the else return line? I don't see it defined.

woooee Your program is working but it's giving me really messy output, it's all on one line an run togather. I tried pring '\n' right after the print statement but that doesn't seem to be getting the job done. Any ideas?

0

Gribouillis where did the parameter mode come from in the else return line?

It is defined at line 7. The else part is executed if line 7 succeeds.

Edited by Gribouillis

0

@woooee Your program is working but it's giving me really messy output, it's all on one line an run togather. I tried pring '\n' right after the print statement but that doesn't seem to be getting the job done. Any ideas?

split it on the newline, "\n", to get a list of individual lines.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.