Get input in Python
Chris Rebert
clp2 at rebertia.com
Mon Jan 24 01:37:08 EST 2011
On Sun, Jan 23, 2011 at 10:10 PM, Santhosh Kumar
<santhosh.vkumar at gmail.com> wrote:
> Hi all,
> I am trying to get input from the file open(sys.argv[1]). So,
> while executing I will refer it as python filename.py sample_file.txt this
> will root to my sys.argv[]. So I need to follow the same but I also need to
> give input Example : python filename.py <input_text> <sample_file.txt>. How
> should I do coding for this.
Just access the text using sys.argv like before. It's just another
element in the list; there's nothing special about it. You just need
to change the indices accordingly:
from sys import argv
text = argv[1]
filepath = argv[2]
# alternatively:
# text, filepath = argv[1:]
print("Your text input was:")
print(text)
print("The file's contents are:")
with file(filepath, 'r') as f:
print(f.read())
Usage:
$ python 'Hello there Santhosh' something.txt
Your text input was:
Hello there Santhosh
The file's contents are:
<contents of something.txt here>
Note that the text is quoted; this is required if your text contains
spaces and/or shell special characters.
Cheers,
Chris
--
http://blog.rebertia.com
More information about the Python-list
mailing list