Python: Trying to restart script not working
<p>Tried to restart my python script within itself.
Python 2.7.11</p>

<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
os.execv(__file__, sys.argv)
sys.exit()
</code></pre>

<p>Result:</p>

<pre><code>Traceback (most recent call last):
    File "...\foo.py", line 3, in &lt;module&gt;
        os.execv(__file__, sys.argv)
OSError: [Errno 8] Exec format error
</code></pre>

<p>Another code:</p>

<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
os.execv(sys.executable, [sys.executable] + sys.argv)
sys.exit()
</code></pre>

<p>Result:</p>

<pre><code>C:\...\python.exe: can't open file 'C:\...\Math': [Errno 2] No such file or directory
</code></pre>

<p>The file's name is foo.py - it's in a folder name 'Math Project'</p>

<p>Codepage: 852, if necessary.</p>

<p>Your error message <code>C:\...\python.exe</code> suggests that you're running a Windows system. </p>

<p>Your first script fails because under Windows, <code>os.execv()</code> doesn't know how to handle Python scripts because the first line (<code>#!/usr/bin/python</code>) is not evaluated nor does it point to a valid Python interpreter on most Windows systems. In effect, <code>os.execv()</code> tries to execute a plain text file which happens to contain Python code, but the system doesn't know that.</p>

<p>Your second script fails to correctly retrieve the file name of your Python script <code>foo.py</code>. It's not clear to me why that happens, but the error message suggests that there might be a problem with the space in your directory name <code>Math Project</code>. </p>

<p>As a possible workaround, try replacing the line </p>

<pre class="lang-py prettyprint-override"><code>os.execv(sys.executable, [sys.executable] + sys.argv)
</code></pre>

<p>by the following:</p>

<pre class="lang-py prettyprint-override"><code>os.execv(sys.executable, 
         [sys.executable, os.path.join(sys.path[0], __file__)] + sys.argv[1:])
</code></pre>

<p>This line attempts to reconstruct the correct path to your Python script, and pass it as an argument to the Python interpreter.</p>

<p>As a side note: Keep in mind what your script is doing: it's unconditionally  starting another instance of itself. This will result in an infinite loop, which will eventually bring down your system. Make sure that your real script contains an abort condition.</p>

<p><strong>EDIT:</strong> </p>

<p>The problem lies, indeed, with the space in the path, and the workaround that I mentioned won't help. However, the <code>subprocess</code> module should take care of that. Use it like so:</p>

<pre class="lang-py prettyprint-override"><code>import os
import sys
import subprocess

subprocess.call(["python", os.path.join(sys.path[0], __file__)] + sys.argv[1:])
</code></pre>

python exec restart