Home > python > Python from command line

Python from command line

Problem
You want to calculate something with Python quickly, from the command line. You might even want to use Python in a bash script to produce some result.

Solution

$ python -c "print(2*3)"
6

Storing the result in a variable:

$ X=`python -c "print(2*3)"`
$ echo $X
6

Thanks to Tajti A. for the tip.

Update (20170803)
You can also pass a bash variable to the embedded Python:

VAL="cat dog cat"
NEW=`python3 -c "print('$VAL'.replace('dog', 'wolf'))"`
echo $NEW

Output: “cat wolf cat”.

Categories: python Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment

Design a site like this with WordPress.com
Get started