Change Python execution version from Python script

Is it possible to change the version of Python execution in a script?

I have Python 2.6.6, which loads by default. I want to change this version to 3.6.0, which installs in a custom location (not / usr / bin) inside the script. So, in the script, I will check the version of Python with sys.version, load the Python module 3.6.0 into the script. This is not reflected in the runtime. Here is the code:

import sys, os
pyVersion = int(sys.version.split(" ")[0].replace(".", ""))
exec(open(os.environ['MODULESHOME']+"/init/python.py").read())
if pyVersion < 360:
    print("Python 3.6.0 version required")
    print("Loading utils/python module")
    module(['load', 'utils/python/3.6.0'])
    module('li')

It lists the modules as expected. Output:

Python 3.6.0 version required
Loading utils/python module
Currently Loaded Modulefiles:
1) licenses                    2) cliosoft/6.32.p3(default)   3)utils/python/3.6.0

Now when I check the python version in the next line, it is still python 2.6.6

print(sys.version)

Conclusion:

2.6.6 (r266:84292, Jul 23 2015, 15:22:56) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)]

Now, how can I get Python to use 3.6.0 for all lines of code after loading the module?

. script. , root. , . .

+4
1

" DOC". Python "docstrings" (""). :

#!/usr/bin/env python

# Python 2
import os
import sys
print "1. Python version: ", sys.version
print "2. Process id: ", os.getpid()

os.execlp("python3", "python3", "-c", """

# Python 3
import os
import sys
print("3. Python version: ", sys.version)
print("4. Process id: ", os.getpid())
""")

print "5. Does not execute"

(Ubuntu 16.04) :

1. Python version:  2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609]
2. Process id:  3085
3. Python version:  3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609]
4. Process id:  3085

( .)

:

  • 2. * 3. *
  • 3085
  • exec . exec "" Python 2. .

" Python 2. * 3. *". 2.6.6 3.6.0.

, . , , . :

  • exec .
  • arg ( Python 3) . .
  • , , script docstring.
+1

Source: https://habr.com/ru/post/1668509/


All Articles