0

I tried multiple times to make this work without results, here's the code

import os, sys

try:
    with open("syscore.lib", "r") as confFile:
        readConfFile = confFile.readlines()
        fileExist = True                                                  
except:
    fileExist = False

if fileExist is True:
    method = "r"
else:
    method = "w"                                                          
for _ in range(2):
    with open("syscore.lib", method) as confFile:
        try:
            readConfFile = confFile.readlines()
    except:
        confFile.write(os.system("python --version").replace("Python ", ""))
print(readConfFile)

The problem come again in a similar way down here

import os

test = [str(os.system('python --version'))]
test1 = os.system('python --version')

print('PV: '+str(test1))
print('Python Version: '+test[0])

Can anyone help me with this? Thanks

2 Answers2

0

As noted in the relevant thread here, os.system() returns the process exit value. 0 means success. If you want to capture the printed output, use os.popen() instead:

import os


python_version = os.popen("python -V").read().strip()

And the output is 'Python 3.6.6'.

Hope this helps.

Sergii Shcherbak
  • 837
  • 1
  • 11
  • 12
  • `os.popen()` is not particularly brilliant, it's just a wrapper for the proper functionality. You want `subprocess.check_output()` but of course calling Python in a subprocess from Python itself to find its version number is just silly. – tripleee Aug 26 '19 at 11:13
0

if you only want to get python version then try,

Python 2.7.12 (default, Nov 12 2018, 14:36:49) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
>>> version = "{}.{}.{}".format(*sys.version_info)
'2.7.12'
>>> 

you will get in python3,

Python 3.5.2 (default, Nov 12 2018, 13:43:14) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> "{}.{}.{}".format(*sys.version_info)
'3.5.2'
>>> 

or you can use,

>>> import sys
>>> sys.version
'3.5.2 (default, Nov 12 2018, 13:43:14) \n[GCC 5.4.0 20160609]'
>>> 
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118