Python Running from Command line

To run Python on Unbutu Command line

run command
$ python2.7
or
$ python3.5
or simply
$ python

Note: The last one (python) command will start the default version…
You will see below screen
python3.5
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type “help”, “copyright”, “credits” or “license” for more information.
>>>
Enter Python Code directly
>>> print (“Write on Console”)
Write on Console

Running Python file from command line
Enter command
$ python2.7 myfile.py
or
$ python3.5 myfile.py
or simpy
$ python myfile.py

To get argument from command line
Enter command
$ python myfile.py arg1, arg2, arg3

and your code in file should look like;

import sys
print (sys.argv)
file_name = sys.argv[0]
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
sum = num1 + num2
print (str(num1) + " + " + str(num2) + " = " + str(sum))

Note: the first argument will always be the name of a file, to get arguments other than file, use >> sys.agrv[1:]
Note: All argument are sent as of string data type.

Arguments Handling

import sys
print ("All Args: " + str(sys.argv))
print ("File Name: " + sys.argv[0])
print ("Other Args: " + str(sys.argv[1:]))
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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