Ashish
Ashish

Reputation: 479

Python - Giving Commands as argument

Is it possible to give the command to Python as argument instead of writing it in a file?

For example contents of file Hello.py are :

=========================
print"Hello World!"
=========================

When we do :

$ Python Hello.py

Its says :

Hello World!

But is it possible to give command diretly as Python argument : Like :

$python <Some Option> "print 'hello World!'"

Upvotes: 1

Views: 87

Answers (2)

user2088432
user2088432

Reputation: 375

import sys
cmdargs = sys.argv
print cmdargs[1]

$python file.py this_is_argument

this_is_argument

It takes the input from command line and prints the same.

Upvotes: 0

sloth
sloth

Reputation: 101052

You can use the -c option:

Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code.

Example:

python -c "print 'Hello World!'"

Upvotes: 3

Related Questions