0

I have to write a script, which should be python 2/3 compatible. I need to use the input method and it should accept inputs without quotes. Python 3 supports only raw_input for that and Python 2 does only support input for that

I wrote a method that checks the python version and uses the corresponding input method (as shown below)

The Problem is:

output = os.popen('python --version').readlines()

returns

Python 2.7.15rc1
[]

So the list is actually empty despite the line beeing printed

If I change the text to ask for the git version

output = os.popen('git --version').readlines()

it returns

['git version 2.17.1\n']

like it should.

How can it be that this method is behaving so odd? And has anybody an idea how to fix that?

I tried to run it on both python 2 and 3.

def input_23_comp(text=''):    
    output = os.popen('python --version').readlines()
    output = output[0].strip() 
    if (output[0:8] == 'Python 2'):
        raw_input(text)
    else:
        input(text)

1 Answers1

2

python --version prints version info to stderr. You're capturing stdout. You need to capture stderr, or redirect stderr to stdout.

If you want to check the version of Python you're running on, though, running python --version is the wrong way to go. The version you invoke through that command may not even be the version you're running on. Use sys.version_info.

user2357112
  • 260,549
  • 28
  • 431
  • 505