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>You have a few options:</p>

<ul>
<li>Run your script as root or with sudo</li>
<li>Set the setuid bit and have root own the script (although on many systems this won't work with scripts, and then the script will be callable by anyone)</li>
<li>Detect that you're not running as root (<code>os.geteuid() != 0</code>), then call yourself with <code>sudo</code> infront (which will ask the user to enter their password) and exit:</li>
</ul>

<p>â</p>

<pre><code>import os
import sys
import subprocess

if os.geteuid() == 0:
    print("We're root!")
else:
    print("We're not root.")
    subprocess.call(['sudo', 'python3', *sys.argv])
</code></pre>

<p>Calling it looks like this:</p>

<pre><code>$ python3 be_root.py
We're not root.
Password:
We're root!
</code></pre>

python file-writing ioerror