How do I check what version of Python is running my script?

前端 未结 22 2046
醉话见心
醉话见心 2020-11-22 04:11

How can I check what version of the Python Interpreter is interpreting my script?

相关标签:
22条回答
  • 2020-11-22 04:38

    Here's a short commandline version which exits straight away (handy for scripts and automated execution):

    python -c "print(__import__('sys').version)"
    

    Or just the major, minor and micro:

    python -c "print(__import__('sys').version_info[:1])" # (2,)
    python -c "print(__import__('sys').version_info[:2])" # (2, 7)
    python -c "print(__import__('sys').version_info[:3])" # (2, 7, 6)
    
    0 讨论(0)
  • 2020-11-22 04:38

    The simplest way

    Just type python in your terminal and you can see the version as like following

    desktop:~$ python
    Python 2.7.6 (default, Jun 22 2015, 18:00:18) 
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 
    
    0 讨论(0)
  • 2020-11-22 04:38

    A attempt using os.popen to read it in a variable:

    import os
    ver = os.popen('python -V').read().strip()
    print(ver)
    
    0 讨论(0)
  • 2020-11-22 04:39

    Your best bet is probably something like so:

    >>> import sys
    >>> sys.version_info
    (2, 6, 4, 'final', 0)
    >>> if not sys.version_info[:2] == (2, 6):
    ...    print "Error, I need python 2.6"
    ... else:
    ...    from my_module import twoPointSixCode
    >>> 
    

    Additionally, you can always wrap your imports in a simple try, which should catch syntax errors. And, to @Heikki's point, this code will be compatible with much older versions of python:

    >>> try:
    ...     from my_module import twoPointSixCode
    ... except Exception: 
    ...     print "can't import, probably because your python is too old!"
    >>>
    
    0 讨论(0)
  • 2020-11-22 04:39

    If you want to detect pre-Python 3 and don't want to import anything...

    ...you can (ab)use list comprehension scoping changes and do it in a single expression:

    is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)
    
    0 讨论(0)
  • 2020-11-22 04:39

    Check Python version: python -V or python --version or apt-cache policy python

    you can also run whereis python to see how many versions are installed.

    0 讨论(0)
提交回复
热议问题