1

I have to install different modules according to the version of Python installed on a machine.

A previous question asked how to do this, but it only prints the result to screen. For instance:

$ python -c 'import sys; print sys.version_info'
sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0)

or rather:

$ python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))'
2.7.3

On a Bash shell, how can I "catch" the printed line above so that I can incorporate its value in an if-statement?

EDIT: OK, now I realize it was very simple. I got stuck initially with:

a=$(python --version)

... because it didn't assign anything to the variable a, it only printed the version to screen.

1
  • 1
    python --version outputs to STDERR due to which it only printed the version to screen. Commented Jan 21, 2014 at 13:21

3 Answers 3

3

You can assign the value to a variable:

pyver=$(python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))')

please, note that there are no spaces around the =.

Now, you can use it in your if statement:

if [[ "$pyver" == "2.7.0" ]]; then
    echo "Python 2.7.0 detected"
fi
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this:

if [[ $(python --version 2>&1) == *2\.7\.3 ]]; then
  echo "Running python 2.7.3";
  # do something here
fi

Note that python --version outputs to STDERR so you'd need to redirect it to STDOUT.

In order to assign it to a variable,

a=$(python --version 2>&1)

2 Comments

ooh ok, that's what I was missing. How could I have figured it out on my own that it was printing to STDERR? Just by guessing and trying?
@RickyRobinson When it didn't redirect the output to the variable and printed on the screen instead, you could have said python --version 2>/dev/null to see what happens.
1

Use command substiution (`` or $()):

if [ $(python ...)  == 2.7.3 ]
then
 ...
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.