3

I am using pipenv for managing my packages. I want to write a python script that calls another python script that uses a different Virtual Environment(VE).

How can I run python script 1 that uses VE1 and call another python script (script2 that uses VE2).

I found this code for the cases where there is no need for changing the virtual environment.

import os
os.system("python myOtherScript.py arg1 arg2 arg3") 

The only idea that I had was simply navigating to the target project and activate shell:

os.system("cd /home/mmoradi2/pgrastertime/")
os.system("pipenv  shell")
os.system("python test.py")

but it says:

Shell for /home/..........-GdKCBK2j already activated. No action taken to avoid nested environments.

What should I do now? in fact my own code needs VE1 and the subprocess (second script) needs VE2. How can I call the second script inside my code?

In addition, the second script is used as a command line tool that accepts the inputs with flags:

python3 pgrastertime.py -s ./sql/postprocess.sql -t brasdor_c_07_0150  
-p xml -f  -r ../data/brasdor_c_07_0150.object.xml 

How can I call it using the solution of @tzaman

1 Answer 1

3

Each virtualenv has its own python executable which you can use directly to execute the script.

Using subprocess (more versatile than os.system):

import subprocess

venv_python = '/path/to/other/venv/bin/python'
args = [venv_python, 'my_script.py', 'arg1', 'arg2', 'arg3']
subprocess.run(args)    
Sign up to request clarification or add additional context in comments.

4 Comments

subprocess is in the standard library, you don't need to install anything. If you're on Python 2, run doesn't exist since it was added in 3.5+ but you can use subprocess.call instead; read the linked documentation for the "Older high level API".
actually my second srcipt that I want to call accepts flags: pgrastertime.py -s ./sql/postprocess.sql -t brasdor_c_20190507_0150 -p xml -f how can I import the flags using your code?
@milad just add all the flags to the args list in order.
I had an error. Permission denied: PermissionError: [Errno 13] Permission denied: '/home/mmoradi2/.local/share/virtualenvs/pgrastertime-d4CrnaVY/bin/activate'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.