Anthony Oteri Anthony Oteri - 1 year ago 72
Linux Question

What is the recommended way to update a proc entry from Python

I have a linux proc entry in

which toggles a flag in a custom kernel module. Setting the value to 1 will enable a mode in the module, setting to 0 will disable that mode.

In bash, to enable the mode, I would simply do

echo 1 > /proc/sys/fs/offs/ts/enable

And to disable it,

echo 0 > /proc/sys/fs/offs/ts/enable

I have a daemon written in Python 2.7 which will look for some external event trigger, and when that event fires, should enable or disable the feature in the kernel module. The daemon is run with root privileges, so I shouldn't run into any kind of permissions issues.

Is there a recommended way of setting this value from python?

For example, say my function right now looks like this.

def set_mode(enable=True):
with open('/proc/sys/fs/offs/ts/enable', 'w') as p:
if enable:

Answer Source

There are a couple of problems with your code.

Firstly, you want to write to the file, but you're opening it in read mode.

Secondly, .write expects string data, not an integer.

We can get rid of the if test by exploiting the fact that False and True have integer values of 0 & 1, respectively. The code below uses the print function rather than .write because print can convert the integer returned by int(enable) to a string. Also, print appends a newline (unless you tell it not to via the end argument), so this way the Python code performs the same action as your Bash command lines.

def set_mode(enable=True):
    with open('/proc/sys/fs/offs/ts/enable', 'w') as p:
        print(int(enable), file=p)

If you want to do it with .write, change the print line to:

p.write(str(int(enable)) + '\n')

There's a way to do that conversion from boolean to string in one step: use the boolean to index into a string literal:


It's short & fast, but some would argue that it's a little cryptic to use booleans as indices.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download