Python: Redirecting to tty and reading from tty

In bash, you can do something like this:

#!/bin/bash
echo -n "What is your name? " > /dev/tty
read thename < /dev/tty

How can I do the same in python?

I have a python script that has the following content:

#!/usr/bin/python2.7

import getpass
import sys
import telnetlib
import time
print ""
uip = raw_input("Enter your IP Address: ")
print ""
uname = raw_input("Enter your username: ")
print ""
upass = getpass.getpass("Enter your password: ")
tn = telnetlib.Telnet(uip)
print ""
print "Successfully Connected to", uip
print ""

The bash script works even when it is run through a pipe as in:

cat bashscript.sh | bash

Whereas the python script doesnt work when run like this:

cat pythonscript.py | python

I need to be able to read from tty when running a script through a pipe.

Hi...

I am missing something, why do you need a python script to be piped into python?
You are already calling python in your shebang...
Longhand OSX 10.13.4, default bash terminal.

Last login: Wed May 16 17:56:35 on ttys000
AMIGA:barrywalker~> cd Desktop/Code/Python
AMIGA:barrywalker~/Desktop/Code/Python> chmod 755 test.py
AMIGA:barrywalker~/Desktop/Code/Python> cat test.py
#!/usr/bin/python
import sys
print("This is a test line.")
text = raw_input("Enter your name: ")
print(text)
sys.exit()
AMIGA:barrywalker~/Desktop/Code/Python> ./test.py
This is a test line.
Enter your name: My name is Bazza...
My name is Bazza...
AMIGA:barrywalker~/Desktop/Code/Python> _

Security through obscurity. Skysmart runs programs through a long train of generators and mutators in the theory that this will prevent people from wanting to use it anywhere else.

1 Like