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.

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'

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

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
"""

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?

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.

@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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.