Friday, July 22, 2022

[SOLVED] how to run chmod in python?

Issue

I was working with a sensor called Rplidar. To connect the Rplidar with my operating system(Ubuntu) sometimes i have to use this command in the terminal:

sudo chmod 666 /dev/ttyUSB0  

After running this instruction, ubuntu can detect the Rplidar. Later on, i will run a python script to work with the Rplidar. Now I want to include this command inside my python script so that i do not need to run it in the terminal before working with the Rplidar. Is there any way that i could do it in python script?


Solution

The simple answer is that chmod is provided in the os module in Python:

so all you need to do is run:

import os
filename = 'example.dat'
os.chmod(filename,
    stat.S_IRUSR |
    stat.S_IWUSR |
    stat.S_IRGRP |
    stat.S_IWGRP |
    stat.S_IROTH)

so there's no need to shell out to perform this operation normally. Also have a look at the os.path and shutil modules for much more support in this area.

Things get a little complicated if you need to perform this operation with elevated privileges, but that's actually not the solution here.

Also, it is not a good idea to give 666 permissions to system devices. This can open up security problems when any user on the system has read/write access to system devices. As a matter of principle, use the least permissions required for correct operation.

As @KlausD. comments, you shouldn't be forcing permission changes on these device nodes anyway. The correct approach is to perform a one-time operation of adding the relevant user to the dialout group on your system. Then by being in the correct group, the user running your application will have access to the device. This is already answered here:

Just run this once:

sudo adduser kazi dialout

then log out and back in for it to take effect. Your Rplidar app will run fine.



Answered By - gavinb
Answer Checked By - Marie Seifert (WPSolving Admin)