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


Asked by: Marcus887 | Posted: 01-10-2021






Answer 1

Call

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

and

print 'You said', name

Answered by: Arthur860 | Posted: 02-11-2021



Answer 2

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.

Answered by: Thomas950 | Posted: 02-11-2021



Answer 3

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

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

Answered by: Brad373 | Posted: 02-11-2021



Answer 4

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)

Answered by: Brooke518 | Posted: 02-11-2021



Similar questions

swift - How would I allow my IOS app communicate with my python script

I'm developing a product where it shows information about stuff, the product involves a raspberry pi which automatically runs a python program on boot. When it's the users first time using this product they will have to set it up (log into their account etc.). I'd like it for the IOS app to recognize that the product is nearby and allow the user to enter the necessary data (WiFi information, login credentials, etc.) for th...


Communicate (IPC) between C++ to Python

I have application server (server.py) and C + + as a client (client.exe). Client.exe send variable to server.py via 'named pipes'. The problem is when I send eg "Default message from client" from client.exe in server.py only produce "D" (only first character send). Can anyone help me?? C++ server.py from ctypes import * PIPE_ACCESS_DUPLEX = 0x3 PIPE_TYPE_MES...


python - How to communicate between C++ server app and django web app

I have some framework doing specific task in C++ and a django-based web app. The idea is to launch this framework, receive some data from it, send some data or request and check it's status in some period. I'm looking for the best way of communication. Both apps run on the same server. I was wondering if a json server in C++ is a good idea. Django would send a request to this server, and server would parse it, and ...


How do c++ communicate with python?

Closed. This question needs details or clarity. It ...


python - Popen hangs on communicate

I am writing a program to communicate to two programs: output = Popen(shlex.split(query_cmd), stdout=PIPE,stdin=None) cmd_out = [output.stdout] while cmd_out: readable,writeready,exceptready = select.select(cmd_out,[],[],timeout) for f in readable: line = f.readline() snap_result=Popen(shlex.split("snap %s" % (line) ),stdout=PIPE,close_fds=True).communicate()[0] print snap_result ...


python - How do Bottle and HTML communicate back and forth?

So I am attempting to use bottle.py and twitter bootstrap together to make a small website. I need to be able to insert a reasonable amount of data at various points in the HTML using Python but I am not really sure I understand how the HTML and python are communicating. Here is ...


python - socket can't communicate with netcat bash

On a vm I used the command: nc -l -p 8221 -e /bin/bash and made a python3 script: def netcat(): print ("starting connection") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("192.168.1.60", 8221)) while True: user = input("what to send?: ") s.sendall(bytes(user, "utf-8")) time.sleep(5) word = "bob" data = s.recv(4096) if d...


python - how to communicate between client and server?

Closed. This question needs details or clarity. It ...


python - how to communicate with a router

I have written a script to perform telnet, which i wanted to use for sending commands to my Device Under Test (router). My Telnet Script: import sys, time, telnetlib sys.path.insert(0, '/tmp') import options def telnet_connect(): HOST = "%s" %options.DUT_telnet_ip PORT = "%s" %options.DUT_telnet_port username = "%s" %options.DUT_telnet_username password = "%s" %opt...


python - How to get For loops to communicate with a While loop

I need to write a program that takes the last number from the for loop ( if it exceeds a certain number) and places it in the while loop. I have left the unfinished code below. t=0 num=int(input("How many presents do you want to buy?: ")) for i in range(num): t=t+int(input("Please enter the price of a present") while t&gt;'200': print("Limit Exceeded.") print("You need to get rid of t...


python - How to communicate with an UART?

I am trying to execute a python file, i am a beginner in python, I installed the WinPython-64bit-2.7.6.4, I open the WinPython Command Prompt.exe, I try to execute this file: import serial ser = serial.Serial('COM4') # open serial port print(ser.name) # check which port was really used ser.write(b'hello') # write a string ser.close() # close port The result that ...


python - How can I set it up so that threads communicate they're complete with their task?

Conceptually, I would like to accomplish the following but have had trouble understand how to code it properly in Python: from threading import Thread for i in range(0,3): t = Thread(target=myfunction) t.start() # wait until threads have finished executing print 'complete!'


How to communicate between Python and C# using XML-RPC?

Assume I have a simple XML-RPC service that is implemented with Python: from SimpleXMLRPCServer import SimpleXMLRPCServer # Python 2 def getTest(): return 'test message' if __name__ == '__main__' : server = SimpleXMLRPCServer(('localhost', 8888)) server.register_function(getTest) server.serve_forever() Can anyone tell me how to call the...


windows - Using pipes to communicate data between two anonymous python scripts

Consider this at the windows commandline. scriptA.py | scriptB.py I want to send a dictionary object from scriptA.py to scriptB.py by pickle:ing it and sending it over a pipe. But I don't know how to accomplish this. I've read some posts about this subject here, but usually there's answers along these line: Popen( "scriptA.py"´, ..., and so on ) Bu...


python - Communicate with backend job from web server or web page

I have an "appliance" (for lack of better description) running linux. Currently I ssh into the box to launch jobs. This isn't friendly enough for my users, so I'm putting together a simple web UI to launch the script. A job runs for anywhere from 10 seconds to several hours. The web UI needs to reflect the status of the job. I've solved similar problems in the past by running a daemon on the server that wat...


python - How do you know when two objects can communicate?

class GuiMaker(Frame): #more code def __init__(self, parent=None): Frame.__init__(self, parent) self.pack(expand=YES, fill=BOTH) # make frame stretchable self.start() # for subclass: set menu/toolBar self.makeMenuBar() # done here: build menu-bar self.makeToolBar() # done here: build tool-bar...


python - Can you only communicate once with a subprocess?

communicate's documentation says: Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. What do you do if you need to send input to a process more than once ? For exam...


python - communicate with a process in utf-8 on a cp1252 consoless

I need to control a program by sending commands in utf-8 encoding to its standard input. For this I run the program using subprocess.Popen(): proc = Popen("myexecutable.exe", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) proc.stdin.write(u'ééé'.encode('utf_8')) If I run this from a cygwin utf-8 console, it works. If I run it from a windows console (encoding ='cp1252') this...


python - "post" method to communicate directly with a server

Just started with python not long ago, and I'm learning to use "post" method to communicate directly with a server. A fun script I'm working on right now is to post comments on wordpress. The script does post comments on my local site, but I don't know why it raises HTTP Error 404 which means page not found. Here's my code, please help me find what's wrong: import urllib2 import urllib url='http://localhos...


python - twisted: how to communicate elegantly between reactor code and threaded code?

I have a client connected to a server using twisted. The client has a thread which might potentially be doing things in the background. When the reactor is shutting down, I have to: 1) check if the thread is doing things 2) stop it if it is What's an elegant way to do this? The best I can do is some confused thing like: def cleanup(self): isWorkingDF = defer.Deferred() ...


python - Making two scripts communicate

I have to make two programs (for example a "script A" (.py) and "script B"(.exe)) communicate. Both programs are on a infinite loop: Script A needs to write to the stdin of script B and afterwards read the stdout of script B thereafter write again etc. Script B I cannot change. Both files are on my hard disk, so I there must be a better way to solve this than networking. I can, however, write files with script A. T...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top