Tony Tannous
Tony Tannous

Reputation: 14876

Find python version in Tcl script

Is it possible to find out in a .tcl script, what python version is installed? In other words, how can I tell what python version is in default path from a .tcl script?

Tcl Wiki doesn't include useful information about this

currently I am calling a python script which prints sys.version and parsing its output.

.py

import sys

def find_version():
    version = sys.version
    version = version.split()[0].split('.')
    version = version[0] + '.' + version[1]
    print(version)

if __name__ == '__main__':
    find_version()

.tcl

set file "C://find_python_version.py"
set output [exec python $file]

Upvotes: 0

Views: 387

Answers (2)

Hai Vu
Hai Vu

Reputation: 40723

I would use Python's sys.version_info because I can format the version string in any way I like:

set pythonVersion [exec python -c {import sys; print("%d.%d.%d" % sys.version_info[:3])}]
puts "Python version: $pythonVersion"

Output: Python version: 2.7.15

A couple of notes:

  • A Python script (in curly braces) follows the -c flag will print out the version in the form x.y.z, you can format it any way you like
  • The value of sys.version_info is a list of many elements, see documentation. I am interested only in the first 3 elements, hence sys.version_info[:3]
  • The print statement/function with parentheses will work with both Python 2 and Python 3

Upvotes: 1

Donal Fellows
Donal Fellows

Reputation: 137567

A simple enough approach seems to be to parse the result of python --version:

proc pythonVersion {{pythonExecutable "python"}} {
    # Tricky point: Python 2.7 writes version info to stderr!
    set info [exec $pythonExecutable --version 2>@1]
    if {[regexp {^Python ([\d.]+)$} $info --> version]} {
        return $version
    }
    error "failed to parse output of $pythonExecutable --version: '$info'"
}

Testing on this system:

% pythonVersion
3.6.8
% pythonVersion python2.7
2.7.15

Looks OK to me.

Upvotes: 1

Related Questions