Python script not able to read user input when run remotely
Question: I am trying to remotely execute a simple python script userinfo.py present in
remotehost.

Below is sourcecode of userinfo.py [ using Python 2.7.10 ]

    
    
    #############
    print "Userinfo :"
    name=raw_input("Enter your name")
    age=raw_input("Enter your age")
    print "Name"+name+"\nAge"+age
    #############
    

But script is working abnormally when run remotely.

    
    
    [user@localhost]# ssh remotehost python /home/userinfo.py
    

> Userinfo :
>
> Enter your nameEnter your ageName
>
> Age
>
> [user@localhost]#
>
> Execution summary ::

During execution, it doesn't print anything, it directly waits for user input
and I just pressed Enter key it will display output as above.

Would like to know why it is not behaving as expected when raw_input is used.

When values are passed as arguments, it works fine.

> [user@localhost]# ssh remotehost python userinfo.py xyz 20
>
> Userinfo :
>
> Name xyz
>
> Age 20
>
> [user@localhost]#

below is changed code.

    
    
    ###########
    import sys
    print "Userinfo :"
    name=sys.argv[1]
    age=sys.argv[2]
    print "Name "+name+"\nAge "+age
    ############
    

Would like to know why interactive way is not working as expected and what may
be fix.


Answer: In a regular terminal, the raw_input prompt is flushed immediately, meaning
you will see the prompt "Enter Your Name".

If you run this script through ssh, it saves the output until the script it
finished and only then prints everything in the buffer.

What you need is to run python unbuffered, which will force stdout to flush
after every output, and thus display to your ssh session. This can be
accomplished several ways.

    
    
    ssh user@remotehost python -u script.py
    

or make the file executable _and_ unbuffered by adding the following to top of
your .py script. Be sure to use your actual python path here:

    
    
    #! /usr/bin/python - u
    

and then in make it executable

    
    
    sudo chmod +x script.py
    

then

    
    
    ssh user@remotehost ./script.py
    

