0
votes

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

2

2 Answers

1
votes

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.

1
votes

There is another simpler way to do what you want. If you want a python script to use a virtualenv you can always use the python interpreter from the virualenv itself.

/Users/Ru/Desktop/mio/worker/venv/bin/python my_python_file.py

This will run the my_python_file.py with the properties/libraries of the virtualenv.

If you want to run that file inside a subprocess you can do something similar to the method I described above:

import subprocess 
subprocess.Popen(['/Users/Ru/Desktop/mio/worker/venv/bin/python my_python_file.py])

and have my_python_file.py import pika and do other actions you wish to do.

Tom.