Nick Stinemates
Nick Stinemates

Reputation: 44190

How can the user communicate with my python script using the shell?

How can I implement the following in python?

#include <iostream>

int main() {
   std::string a; 
   std::cout <<  "What is your name? ";
   std::cin >> a; 
   std::cout << std::endl << "You said: " << a << std::endl;
}

Output:

What is your name? Nick

You said: Nick

Upvotes: 3

Views: 757

Answers (4)

orip
orip

Reputation: 75457

print "You said:", raw_input("What is your name? ")

EDIT: as Swaroop mentioned, this doesn't work (I'm guessing raw_input flushes stdout)

Upvotes: 3

Alex R
Alex R

Reputation: 2221

The simplest way for python 2.x is

var = raw_input()
print var

Another way is using the input() function; n.b. input(), unlike raw_input() expects the input to be a valid python expression. In most cases you should raw_input() and validate it first. You can also use

import sys
var = sys.stdin.read()
lines = sys.stdin.readlines()
more_lines = [line.strip() for line sys.stdin]

sys.stdout.write(var)
sys.stdout.writelines(lines+more_lines)
# important
sys.stdout.flush()

As of python 3.0, however, input() replaces raw_input() and print becomes a function, so

var = input()
print(var)

Upvotes: 1

Swaroop C H
Swaroop C H

Reputation: 17034

Call

name = raw_input('What is your name?')

and

print 'You said', name

Upvotes: 7

S.Lott
S.Lott

Reputation: 391872

Look at the print statement and the raw_input() function.

Or look at sys.stdin.read() and sys.stdout.write().

When using sys.stdout, don't forget to flush.

Upvotes: 3

Related Questions