Search code examples
pythonsubprocessvirtualenv

subprocess open ('source venv/bin/activate'),no such file?


I want get into virtual environment in python files.But it raise no such files.

import subprocess 
subprocess.Popen(['source', '/Users/XX/Desktop/mio/worker/venv/bin/activate'])

Traceback (most recent call last): File "/Users/Ru/Desktop/mio/worker/run.py", line 3, in subprocess.Popen(['source', '/Users/Ru/Desktop/mio/worker/venv/bin/activate'])

File"/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in init errread, errwrite)

File"/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child raise child_exception

OSError: [Errno 2] No such file or directory


Solution

  • I think your code doesn't work because you are separating the 'source' command from the virtualenv path argument, from the documentation:

    "Note in particular that options (such as -input) and arguments (such as eggs.txt) that are separated by whitespace in the shell go in separate list elements, while arguments that need quoting or backslash escaping when used in the shell (such as filenames containing spaces or the echo command shown above) are single list elements."

    You should try one of two things: First, write the source and the virtualenv file path as a single string argument:

    import subprocess 
    subprocess.Popen(['source '/Users/XX/Desktop/mio/worker/venv/bin/activate'])
    

    I'm working on OSX and that doesn't seem to work, but it might be due to the shell you are using. To ensure this will work, you can use the shell=True flag:

    import subprocess
    subprocess.Popen(['source '/Users/XX/Desktop/mio/worker/venv/bin/activate'],shell=True)
    

    This will use /bin/sh shell by default. Again, you can read more in the documentation.

    Tom.