Write to a file with sudo privileges in Python
<p>The following code throws an error if it's run by a non-root user for a file owned by root, even when the non-root user has sudo privileges:</p>

<pre><code>try:
  f = open(filename, "w+")
except IOError:
  sys.stderr.write('Error: Failed to open file %s' % (filename))
f.write(response + "\n" + new_line)
f.close()
</code></pre>

<p>Is there a way to run <code>open(filename, "w+")</code> with sudo privileges, or an alternative function that does this?</p>

<p>Having possibility to using <code>sudo</code> don't give you any privileges if you don't actually use it. So as other guys suggested you probably should just start your program with use of <code>sudo</code>. But if you don't like this idea (I don't see any reason for that) you can do other trick.</p>

<p>Your script can check if is run with root privileges or if it work only with user privileges. Than script can actually run itself with higher privileges. Here you have an example (please note that storing password in source code isn't a good idea). </p>

<pre><code>import os.path
import subprocess

password_for_sudo = 'pass'

def started_as_root():
    if subprocess.check_output('whoami').strip() == 'root':
        return True
    return False

def runing_with_root_privileges():
    print 'I have the power!'

def main():
    if started_as_root():
        print 'OK, I have root privileges. Calling the function...'
        runing_with_root_privileges()
    else:
        print "I'm just a user. Need to start new process with root privileges..."
        current_script = os.path.realpath(__file__)
        os.system('echo %s|sudo -S python %s' % (password_for_sudo, current_script))

if __name__ == '__main__':
    main()
</code></pre>

<p>Output:</p>

<pre><code>$ python test.py
I'm just a user. Need to start new process with root privileges...
OK, I have root privileges. Calling the function...
I have the power!

$ sudo python test.py
OK, I have root privileges.
Calling the function...
I have the power!
</code></pre>

python file-writing ioerror