Kadaj13
Kadaj13

Reputation: 1541

Changing python version environment inside python script

I have two python scripts, first one (script1) works with python2 and second one (script2) works with python3.

They are two codes that I have not written by myself, and I have tried running the first one with python3 or runnig the second one with python2 it wont work.

What I need is to call the script1 many times from script2 (so in script2, I need to call script1 with passing some arguments such as x, y)

So definitely because script1 should run in python2 and script2 should run in python3, I need to change the running environment.

I tried this:

    os.system("source activate py3") #py3 is a virtualenv in which python3 is installed
    #running codes on python3
    os.system("source deactivate py3")
    script1.main(x, y)

however, it seems it doesnt work. if I run python3 script2.py everything will run based on python3 and if I run python script2.py everything will run based on python2.

So it means writing os.system("command to change python version environment") wont work.

Is there any other solution for this?

I appreciate your consideration. Thanks in advnace

Upvotes: 1

Views: 3699

Answers (1)

mementum
mementum

Reputation: 3203

os.system("source activate py3") #py3 is a virtualenv in which python3 is installed

You have run a shell command: source activate py3. That shell command can only have effects inside the call os.system. It doesn't do much and once it's over, your script carry on inside the interpreter, which is already either your python2

So:

#running codes on python3
os.system("source deactivate py3")

the code is NOT running on python3, because whatever you did with os.system had only effects within that call.

One option

os.system('mypy3.sh')

Your mypy3.sh will look like this

#!/bin/sh
source bin/activate
python script_with_python3_code

Upvotes: 1

Related Questions