2

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

milad
  • 204
  • 3
  • 12

1 Answers1

2

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)    
tzaman
  • 46,925
  • 11
  • 90
  • 115
  • 1
    `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". – tzaman Jun 05 '20 at 15:40
  • 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 Jun 05 '20 at 16:49
  • 1
    @milad just add all the flags to the `args` list in order. – tzaman Jun 05 '20 at 18:06
  • I had an error. Permission denied: PermissionError: [Errno 13] Permission denied: '/home/mmoradi2/.local/share/virtualenvs/pgrastertime-d4CrnaVY/bin/activate' – milad Jun 05 '20 at 19:45