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”.

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

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: