Controlling a device that only interacts via Hyperterminal using python - python

I am trying to write a basic driver to control a device that only interacts with hyperterminal. All the inputs expect HT formated data and all of the returns include copious equal signs, newlines, and spaces in order to get the formatting correct for human visualization. I am pretty sure that the returns are generating trouble, as I am throwing exceptions a lot, but I am not sure how else I can handle it. Does anyone know of a better way to do this?
Device manual: http://us.startech.com/media/products/PCM815SHNA/Manuals/PCM815SHNA.pdf
import visa
import re
class iopower8(visa.SerialInstrument):
#initialization
def __init__(self,loc):
visa.SerialInstrument.__init__(self,loc)
self.term_chars = '\r' #set terminal characters
self.write('\r\r') #start faux 'Hyperterminal'
def on(self, bank, out):
self.ask("on " + str(bank) + " " + str(out))
for i in range (1,3):#read buffer into void to prevent issues
try:
self.read_raw()
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
return self.status(bank, out)
def off(self, bank, out):
self.ask("of " + str(bank) + " " + str(out))
for i in range (1,3):#read buffer into void to prevent issues
try:
self.read_raw()
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
return self.status(bank, out)
def status(self, bank, port): #enter bank and port # you want to check
self.ask("st " + str(bank))
result = 'Error' #send error message regardless
for i in range (1,13):#all 12 lines need to be read out of the buffer to prevent issues later
try:
stuff = self.read()#read the line to a holding srting, and dump in void if wriong line to clear buffer
if stuff.strip() == ('='*44):
break
except(visa_exceptions.VisaIOError):
break
for i in range(1,9):
try:
stuff = self.read()#read the line to a holding string, and dump in void if wriong line to clear buffer.
if i == port: #this offset will get you to the line with the relevant port's status
result = re.match('(.*?)(ON|OFF)', stuff) #regex to the find the on/off status
#convert to boolean
if result.group(2) == 'ON':
result = True
elif result.group(2) =='OFF':
result = False
else:
result = 'ERROR'
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
return result
def buffer_clear(self): #in case of buffer jamming
while True:
try:
self.read_raw()
except(visa_exceptions.VisaIOError):
break
def all_on(self, bank):
self.ask("on " + str(bank) + " 0")
for i in range (1,3):#read buffer into void to prevent issues
try:
hold = self.read_raw()
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break
def all_off(self, bank):
self.ask("of " + str(bank) + " 0")
for i in range (1,3):#read buffer into void to prevent issues
try:
self.read_raw()
except(visa_exceptions.VisaIOError):
self.buffer_clear()
break

There's nothing special about HiperTerminal. The end of line character is usually '\r\n' or '\n' alone.

Related

How can I fix EOF problem in the second script (below the dotted line)?

This program essentially encodes and decodes a message and code respectively. I only did the decoding part so far. However I keep getting an EOF error even though I made sure to end parentheses, checked my syntax and kept tampering with it. Unfortunately no luck. Anyone know why this error keeps popping up? I would greatly appreciate it. Also I copied both files that i'm using.
from LetterCodeLogic import LCL
def main():
print("Welcome to the LetterCode program")
choice = getChoice()
while choice !=0:
if choice == 1:
#Encode logic...
print()
elif choice == 2:
#Decode logic...
msg = input("Enter your numbers to decode (separate with commas): ")
#send msg to Decode function in LCL class (LetterCodeLogic.py file)
result = LCL.Decode(msg)
print("Your decoded message is: \n" + result)
else:
print("Unknown process...")
print()
choice = getChoice()
print("Thanks for using the Letter Code program")
def getChoice():
c = int(input("Choice? (1=Encode, 2=Decode, 0=Quit): "))
return c
if __name__ == "__main__":
main()
class LCL:
"""Encode/Decode Functions"""
#staticmethod
def Decode(msg):
#separate numbers from msg string (e.g., "1,2,3")
nums = msg.split(",") #produces list of separate items
result = ""
for x in nums:
try:
n = int(x.strip()) #remove leading/trailing spaces...
if n == 0:
c = " "
elif n < 0 or n > 26:
c = "?"
else:
#ASCII scheme has A=65, B=66, etc.
c = chr(n+64)
except ValueError:
c = "?"
result += c #same as: result = result + c
return result
#staticmethod
def Encode(msg):
the "#staticmethod" and "def Encode()" function was empty and that was the end of line parsing error. When I was coding this and ran it, it ran with no problems. So I removed it for the time being.

Issue processing data read from serial port, when displaying it in a Tkinter textbox

So i am reading (and displaying with a tkinter textbox) data from a serial connection, but i can't process the returning data as i would like to, in order to run my tests. In more simple terms, even though the machine response = 0x1 is displayed, i can't read it from the global serBuffer.
Before displaying it to the textbox i would read from inside the test function and then check if the response was in the string, but now that i pass the read data(strings) to a global variable and then try to read it, it doesn't seem to work, UNLESS i remove the serBuffer = "" from readserial. That results in a new issue though. When i press the button to send the command it sends it, but only receives the response after the second time i press it, and every time after. So as a result i get a Fail if i run the test once, but i get a pass everytime after.
Picture with the desired response ( that the test function doesn't read 0x1 and always returns FAIL)
Picture with the non-desired response ( that only receives the response after the second time a press it, and every time after. So as a result i get a Fail if i run the test once, but i get a pass every time after).
import tkinter as tk
import serial
from serial import *
serialPort = "COM3"
baudRate = 115200
ser = Serial(serialPort, baudRate, timeout=0, writeTimeout=0) #ensure non-blocking
#make a TkInter Window
mainWindow = tk.Tk()
mainWindow.wm_title("Reading Serial")
mainWindow.geometry('1650x1000+500+100')
scrollbar = tk.Scrollbar(mainWindow)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
log = tk.Text ( mainWindow, width=60, height=60, takefocus=0)
log.pack()
log.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=log.yview)
#make our own buffer
#useful for parsing commands
#Serial.readline seems unreliable at times too
serBuffer = ""
ser.write(b'\r\n')
def readSerial():
while True:
c = (ser.read().decode('utf-8', 'ignore')) # attempt to read a character from Serial
# was anything read?
if len(c) == 0:
break
# get the buffer from outside of this function
global serBuffer
# check if character is a delimeter
if c == '\r':
serBuffer += "\n" # don't want returns. chuck it
if c == '\n':
serBuffer += "\n" # add the newline to the buffer
# add the line to the TOP of the log
log.insert('1.1', serBuffer)
serBuffer = "" # empty the buffer
else:
serBuffer += c # add to the buffer
mainWindow.after(100, readSerial) # check serial again soon
def test():
command = b" test command \r\n"
ser.write(command)
global serBuffer
time.sleep(0.5)
if "0x1" in serBuffer:
print('PASS')
return 'PASS'
else:
print('FAIL')
return 'FAIL'
button = tk.Button(mainWindow, text="Pone Test", font=40, bg='#b1c62d', command=test)
button.place(relx=0.8, rely=0, relwidth=0.1, relheight=0.05)
# after initializing serial, an arduino may need a bit of time to reset
mainWindow.after(100, readSerial)
mainWindow.mainloop()
Comment: but only receives the response after the second time a press it, and every time after. So as a result i get a Fail if i run the test once, but i get a pass everytime after
Raise the first, timeout from 100 to 500 ore more.
# after initializing serial, an arduino may need a bit of time to reset
mainWindow.after(100, self.readSerial)
To find out the delay for the first response, try the following:
Note: You have to do this without running def readSerial, to prevent concurent empty the in buffer"
command = b" test command \r\n"
self.ser.write(command)
delay = 0.0
# wait until you get `.in_waiting` data.
while not self.ser.in_waiting:
time.sleep(0.1)
delay += 0.1
print('.', end='')
if delay >= 10:
print('BREAK after {} no in_waiting'.format(int(delay * 10)))
break
print('Delay:{}, in_waiting:{}'.format(delay, self.ser.in_waiting))
The following works for me.
Note: I use OOP syntax.
last_command
serBuffer = ""
last_command = None
Copy the ready read_buffer to last_command, empty only read_buffer
def readSerial(self):
while True:
c = (self.ser.read().decode('utf-8', 'ignore')) # attempt to read a character from Serial
# was anything read?
if len(c) == 0:
break
# get the buffer from outside of this function
global serBuffer
# check if character is a delimeter
if c == '\r':
serBuffer += "\n" # don't want returns. chuck it
if c == '\n':
serBuffer += "\n" # add the newline to the buffer
global last_command
last_command = serBuffer
# add the line to the TOP of the log
# log.insert('1.1', last_command)
print('readSerial.last_command:"{}"'.format(bytes(last_command, 'utf-8')))
serBuffer = "" # empty the buffer
else:
serBuffer += c # add to the buffer
print('readSerial:"{}"'.format(bytes(serBuffer, 'utf-8')))
self.after(100, self.readSerial) # check serial again soon
Do test()
def test(self, write=True):
print('test(write={})'.format(write))
if write:
command = b" test command \r\n"
self.ser.write(command)
self.after(500, self.test, False)
elif last_command is not None:
print('last_command:{}'.format(bytes(last_command, 'utf-8')))
if "0x1" in last_command:
print('PASS')
else:
print('FAIL')
else:
# ATTENTION: This could lead to a infinit loop
# self.after(500, self.test, False)
pass
Output:
test(write=True)
readSerial:"b' '"
readSerial:"b' t'"
readSerial:"b' te'"
readSerial:"b' tes'"
readSerial:"b' test'"
readSerial:"b' test '"
readSerial:"b' test c'"
readSerial:"b' test co'"
readSerial:"b' test com'"
readSerial:"b' test comm'"
readSerial:"b' test comma'"
readSerial:"b' test comman'"
readSerial:"b' test command'"
readSerial:"b' test command '"
readSerial:"b' test command \n\r'"
readSerial.last_command:"b' test command \n\r\n'"
test(write=False)
last_command:b' test command \n\r\n'
FAIL
Note: I get FAIL, because there is no 0x1 in last_command as i use PORT = 'loop://' which echo what is writen!
I made some changes, check this one.
def readSerial():
while True:
c = (ser.read(1).decode('utf-8', 'ignore')) from Serial
if len(c) == 0:
break
global serBuffer
if c == '\r':
serBuffer += ""
if c == '\n':
serBuffer += "\n"
log.insert(tk.END, serBuffer)
log.see(tk.END)
log.update_idletasks()
serBuffer = ""
else:
serBuffer += c
mainWindow.after(500, readSerial)

Error - ValueError: invalid literal for int() with base 10: ' '

I am making an online game using the sockets module and pygame in python.
def read_pos(str):
if str is not None:
string = str.split(",")
return int(string[0]), int(string[1])
else:
pass
def make_pos(tup):
return str(tup[0]) + "," + str(tup[1])
def redrawWindow(win,player, player2):
win.fill((255,255,255))
player.draw(win)
player2.draw(win)
pygame.display.update()
def main():
run = True
n = Network()
startPos = read_pos(n.getPos())
p = Player(startPos[0],startPos[1],100,100,(0,255,0))
p2 = Player(0,0,100,100,(255,0,0))
clock = pygame.time.Clock()
while run:
clock.tick(60)
p2Pos = read_pos(n.send(make_pos((p.x, p.y))))
p2.x = p2Pos[0]
p2.y = p2Pos[1]
p2.update()
This is the code I'm using in my client. in my server, the code is as follows
def convertPos(str):
if str is not None:
str = str.split(",")
return int(str[0]), int(str[1])
else:
pass
def make_pos(tup):
return str(tup[0]) + "," + str(tup[1])
pos = [(0,0),(100,100)]
def threaded_client(conn,player):
conn.send(str.encode(make_pos(pos[player])))
reply = " "
while True:
try:
data = conn.recv(2048).decode()
pos[player] = data
if not data:
print("Disconnected")
break
else:
if player == 1:
reply = (pos[0])
else:
reply = (pos[1])
print("Received: ", data)
print("Sending : ", reply)
conn.sendall(str.encode(make_pos(reply)))
except:
break
print("Lost connection")
conn.close()
I am getting the error of ValueError: invalid literal for int() with base 10: ' '.
Can someone tell me why this is happening? The value of str in the function of convertPos() is coming in as a tuple which I am converting into a string and after that into an integer.
As you have converted it to string, the format you have is (x,y), you need to remove the brackets. You need to rewrite your convertPos function as:
def convertPos(str):
if str is not None:
str=str.strip("()")
str = str.split(",")
return int(str[0]), int(str[1])
EDIT You are not using the else part, so you can remove it.
And as #Azat Ibrakov says, you should not convert the tuple to an string, but if you need to do it, you can use ast.literal_eval like this:
import ast
def convertPos(str):
return ast.literal_eval(str)
or use it directly in place of the convertPos function.
Obviously - as others have pointed out, the returned error is because you're trying to convert an empty string (or spaces) to an integer.
But the real issue is that the incoming co-ordinate is malformed. The code is not catching this error. You can write lots of code to determine what the error is, and report an accurate error. Or just plough-on as if everything is fine, but also catch any exception with a reasonable error message.
def convertPos(str):
coord = None
try:
parts = str.split( ',', 2 )
x = int( parts[0] )
y = int( parts[1] )
coord = ( x, y )
except:
raise ValueError( 'Malformed co-ordinate string [' + str.strip() + ']' )
return coord
I suspect the socket code is not buffering a full packet, and maybe what's being processed is something like 122,, whereas the socket buffering needs to keep reading until a full co-ordinate has arrived.
So you could space-pad your co-ordinates to say a block of 11 characters - that way you know you must have received 11 characters to have a valid co-ordinate string. Alternatively use and end-of-coord marker, like a |, and then the socket code keeps buffing the input co-ordinate until that | arrives.

Searching for a USB in Python is returning 'there is no disk in drive'

I wrote up a function in Python that looks for a USB drive based on a key identifier file, however when called upon it returns 'There is no disk in the drive. Please insert a disk into drive D:/' (which is an SD card reader) - is there a way to have it search drive letters based on drives that are 'ready'?
def FETCH_USBPATH():
for USBPATH in ascii_uppercase:
if os.path.exists('%s:\\File.ID' % USBPATH):
USBPATH='%s:\\' % USBPATH
print('USB is mounted to:', USBPATH)
return USBPATH + ""
return ""
USBdrive = FETCH_USBPATH()
while USBdrive == "":
print('Please plug in USB & press any key to continue', end="")
input()
FlashDrive = FETCH_USBPATH()
Had a fix in cmd here however turned out command-prompt based didn't suit my needs.
Finding 'ready' drives may be more trouble that it's worth for your needs. You can probably get away with just temporarily disabling the error message dialog box via SetThreadErrorMode.
import ctypes
kernel32 = ctypes.WinDLL('kernel32')
SEM_FAILCRITICALERRORS = 1
SEM_NOOPENFILEERRORBOX = 0x8000
SEM_FAIL = SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS
def FETCH_USBPATH():
oldmode = ctypes.c_uint()
kernel32.SetThreadErrorMode(SEM_FAIL, ctypes.byref(oldmode))
try:
for USBPATH in ascii_uppercase:
if os.path.exists('%s:\\File.ID' % USBPATH):
USBPATH = '%s:\\' % USBPATH
print('USB is mounted to:', USBPATH)
return USBPATH
return ""
finally:
kernel32.SetThreadErrorMode(oldmode, ctypes.byref(oldmode))
USBdrive = FETCH_USBPATH()
while USBdrive == "":
print('Please plug in our USB drive and '
'press any key to continue...', end="")
input()
USBdrive = FETCH_USBPATH()

How to stop the input function from inserting a new line?

I know I can stop print from writing a newline by adding a comma
print "Hello, world!",
# print("Hello, world!", end='') for Python 3.x
But how do I stop raw_input (or input for Python 3.x) from writing a newline?
print "Hello, ",
name = raw_input()
print ", how do you do?"
Result:
Hello, Tomas
, how do you do?
Result I want:
Hello, Tomas, how do you do?
But how do I stop raw_input from writing a newline?
In short: You can't.
raw_input() will always echo the text entered by the user, including the trailing newline. That means whatever the user is typing will be printed to standard output.
If you want to prevent this, you will have to use a terminal control library such as the curses module. This is not portable, though -- for example, curses in not available on Windows systems.
I see that nobody has given a working solution, so I decided I might give it a go.
As Ferdinand Beyer said, it is impossible to get raw_input() to not print a new line after the user input. However, it is possible to get back to the line you were before.
I made it into an one-liner. You may use:
print '\033[{}C\033[1A'.format(len(x) + y),
where x is an integer of the length of the given user input and y an integer of the length of raw_input()'s string. Though it might not work on all terminals (as I read when I learned about this method), it works fine on mine. I'm using Kubuntu 14.04.
The string '\033[4C' is used to jump 4 indexes to the right, so it would be equivalent to ' ' * 4. In the same way, the string '\033[1A' is used to jump 1 line up. By using the letters A, B, C or D on the last index of the string, you can go up, down, right and left respectively.
Note that going a line up will delete the existing printed character on that spot, if there is one.
This circumvents it, somewhat, but doesn't assign anything to variable name:
print("Hello, {0}, how do you do?".format(raw_input("Enter name here: ")))
It will prompt the user for a name before printing the entire message though.
You can use getpass instead of raw_input if you don't want it to make a new line!
import sys, getpass
def raw_input2(value="",end=""):
sys.stdout.write(value)
data = getpass.getpass("")
sys.stdout.write(data)
sys.stdout.write(end)
return data
An alternative to backtracking the newline is defining your own function that emulates the built-in input function, echoing and appending every keystroke to a response variable except Enter (which will return the response), whilst also handling Backspace, Del, Home, End, arrow keys, line history, KeyboardInterrupt, EOFError, SIGTSTP and pasting from the clipboard. It's very simple.
Note that on Windows, you'll need to install pyreadline if you want to use line history with the arrow keys like in the usual input function, although it's incomplete so the functionality is still not quite right. In addition, if you're not on v1511 or greater of Windows 10, you'll need to install the colorama module (if you're on Linux or macOS, nothing needs to be done).
Also, due to msvcrt.getwch using '\xe0' to indicate special characters, you won't be able to type 'à'. You should be able to paste it though.
Below is code that makes this work on updated Windows 10 systems (at least v1511), Debian-based Linux distros and maybe macOS and other *NIX operating systems. It should also work regardless of whether you have pyreadline installed on Windows, though it'll lack some functionality.
In windows_specific.py:
"""Windows-specific functions and variables for input_no_newline."""
import ctypes
from msvcrt import getwch # pylint: disable=import-error, unused-import
from shared_stuff import ANSI
try:
import colorama # pylint: disable=import-error
except ImportError:
kernel32 = ctypes.windll.kernel32
# Enable ANSI support to move the text cursor
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
else:
colorama.init()
def get_clipboard_data():
"""Return string previously copied from Windows clipboard.
Adapted from <http://stackoverflow.com/a/23285159/6379747>.
"""
CF_TEXT = 1
user32 = ctypes.windll.user32
user32.OpenClipboard(0)
try:
if user32.IsClipboardFormatAvailable(CF_TEXT):
data = user32.GetClipboardData(CF_TEXT)
data_locked = kernel32.GlobalLock(data)
text = ctypes.c_char_p(data_locked)
kernel32.GlobalUnlock(data_locked)
finally:
user32.CloseClipboard()
return text.value
def sigtstp():
"""Raise EOFError from Ctrl-Z since SIGTSTP doesn't exist on Windows."""
raise EOFError
input_code = {
**ANSI,
'CSI': [['\xe0', '\x00'], ''],
'up': 'H',
'down': 'P',
'right': 'M',
'left': 'K',
'end': 'O',
'home': 'G',
'backspace': '\b',
'del': 'S',
}
In unix_specific.py:
"""Functions and variables for Debian-based Linux distros and macOS."""
import sys
import os
import tty
import signal
import termios
from shared_stuff import ANSI
def getwch():
"""Return a single character from user input without echoing.
ActiveState code, adapted from
<http://code.activestate.com/recipes/134892> by Danny Yoo under
the Python Software Foundation license.
"""
file_descriptor = sys.stdin.fileno()
old_settings = termios.tcgetattr(file_descriptor)
try:
tty.setraw(file_descriptor)
char = sys.stdin.read(1)
finally:
termios.tcsetattr(file_descriptor, termios.TCSADRAIN, old_settings)
return char
def get_clipboard_data():
"""Return nothing; *NIX systems automagically change sys.stdin."""
return ''
def sigtstp():
"""Suspend the script."""
os.kill(os.getpid(), signal.SIGTSTP)
input_code = {
**ANSI,
'CSI': ['\x1b', '['],
'backspace': '\x7f',
'del': ['3', '~'],
}
In readline_available.py:
"""Provide functions for up and down arrows if readline is installed.
Basically to prevent duplicate code and make it work on systems without
readline.
"""
try:
import readline
except ImportError:
import pyreadline as readline
from shared_stuff import move_cursor
def init_history_index():
"""Return index for last element of readline.get_history_item."""
# readline.get_history_item is one-based
return readline.get_current_history_length() + 1
def restore_history(history_index, replaced, cursor_position):
"""Replace 'replaced' with history and return the replacement."""
try:
replacement = readline.get_history_item(history_index)
except IndexError:
replacement = None
if replacement is not None:
move_cursor('right', len(replaced) - cursor_position)
print('\b \b' * len(replaced), end='', flush=True)
print(replacement, end='', flush=True)
return replacement
return replaced
def store_and_replace_history(history_index, replacement, old_history):
"""Store history and then replace it."""
old_history[history_index] = readline.get_history_item(history_index)
try:
readline.replace_history_item(history_index - 1, replacement)
except AttributeError:
# pyreadline is incomplete
pass
def handle_prev_history(history_index, replaced, old_history,
input_replaced, history_modified):
"""Handle some up-arrow logic."""
try:
history = readline.get_history_item(history_index - 1)
except IndexError:
history = None
if history is not None:
if history_index > readline.get_current_history_length():
readline.add_history(replaced)
input_replaced = True
else:
store_and_replace_history(
history_index, replaced, old_history)
history_modified = True
history_index -= 1
return (history_index, input_replaced, history_modified)
def handle_next_history(history_index, replaced, old_history,
input_replaced, history_modified):
"""Handle some down-arrow logic."""
try:
history = readline.get_history_item(history_index + 1)
except IndexError:
history = None
if history is not None:
store_and_replace_history(history_index, replaced, old_history)
history_modified = True
history_index += 1
input_replaced = (not history_index
== readline.get_current_history_length())
return (history_index, input_replaced, history_modified)
def finalise_history(history_index, response, old_history,
input_replaced, history_modified):
"""Change history before the response will be returned elsewhere."""
try:
if input_replaced:
readline.remove_history_item(history_index - 1)
elif history_modified:
readline.remove_history_item(history_index - 1)
readline.add_history(old_history[history_index - 1])
except AttributeError:
# pyreadline is also missing remove_history_item
pass
readline.add_history(response)
In readline_unavailable.py:
"""Provide dummy functions for if readline isn't available."""
# pylint: disable-msg=unused-argument
def init_history_index():
"""Return an index of 1 which probably won't ever change."""
return 1
def restore_history(history_index, replaced, cursor_position):
"""Return the replaced thing without replacing it."""
return replaced
def store_and_replace_history(history_index, replacement, old_history):
"""Don't store history."""
pass
def handle_prev_history(history_index, replaced, old_history,
input_replaced, history_modified):
"""Return 'input_replaced' and 'history_modified' without change."""
return (history_index, input_replaced, history_modified)
def handle_next_history(history_index, replaced, old_history,
input_replaced, history_modified):
"""Also return 'input_replaced' and 'history_modified'."""
return (history_index, input_replaced, history_modified)
def finalise_history(history_index, response, old_history,
input_replaced, history_modified):
"""Don't change nonexistent history."""
pass
In shared_stuff.py:
"""Provide platform-independent functions and variables."""
ANSI = {
'CSI': '\x1b[',
'up': 'A',
'down': 'B',
'right': 'C',
'left': 'D',
'end': 'F',
'home': 'H',
'enter': '\r',
'^C': '\x03',
'^D': '\x04',
'^V': '\x16',
'^Z': '\x1a',
}
def move_cursor(direction, count=1):
"""Move the text cursor 'count' times in the specified direction."""
if direction not in ['up', 'down', 'right', 'left']:
raise ValueError("direction should be either 'up', 'down', 'right' "
"or 'left'")
# A 'count' of zero still moves the cursor, so this needs to be
# tested for.
if count != 0:
print(ANSI['CSI'] + str(count) + ANSI[direction], end='', flush=True)
def line_insert(text, extra=''):
"""Insert text between terminal line and reposition cursor."""
if not extra:
# It's not guaranteed that the new line will completely overshadow
# the old one if there is no extra. Maybe something was 'deleted'?
move_cursor('right', len(text) + 1)
print('\b \b' * (len(text)+1), end='', flush=True)
print(extra + text, end='', flush=True)
move_cursor('left', len(text))
And finally, in input_no_newline.py:
#!/usr/bin/python3
"""Provide an input function that doesn't echo a newline."""
try:
from windows_specific import getwch, get_clipboard_data, sigtstp, input_code
except ImportError:
from unix_specific import getwch, get_clipboard_data, sigtstp, input_code
try:
from readline_available import (init_history_index, restore_history,
store_and_replace_history,
handle_prev_history, handle_next_history,
finalise_history)
except ImportError:
from readline_unavailable import (init_history_index, restore_history,
store_and_replace_history,
handle_prev_history, handle_next_history,
finalise_history)
from shared_stuff import ANSI, move_cursor, line_insert
def input_no_newline(prompt=''): # pylint: disable=too-many-branches, too-many-statements
"""Echo and return user input, except for the newline."""
print(prompt, end='', flush=True)
response = ''
position = 0
history_index = init_history_index()
input_replaced = False
history_modified = False
replacements = {}
while True:
char = getwch()
if char in input_code['CSI'][0]:
char = getwch()
# Relevant input codes are made of two to four characters
if char == input_code['CSI'][1]:
# *NIX uses at least three characters, only the third is
# important
char = getwch()
if char == input_code['up']:
(history_index, input_replaced, history_modified) = (
handle_prev_history(
history_index, response, replacements, input_replaced,
history_modified))
response = restore_history(history_index, response, position)
position = len(response)
elif char == input_code['down']:
(history_index, input_replaced, history_modified) = (
handle_next_history(
history_index, response, replacements, input_replaced,
history_modified))
response = restore_history(history_index, response, position)
position = len(response)
elif char == input_code['right'] and position < len(response):
move_cursor('right')
position += 1
elif char == input_code['left'] and position > 0:
move_cursor('left')
position -= 1
elif char == input_code['end']:
move_cursor('right', len(response) - position)
position = len(response)
elif char == input_code['home']:
move_cursor('left', position)
position = 0
elif char == input_code['del'][0]:
if ''.join(input_code['del']) == '3~':
# *NIX uses '\x1b[3~' as its del key code, but only
# '\x1b[3' has currently been read from sys.stdin
getwch()
backlog = response[position+1 :]
response = response[:position] + backlog
line_insert(backlog)
elif char == input_code['backspace']:
if position > 0:
backlog = response[position:]
response = response[: position-1] + backlog
print('\b', end='', flush=True)
position -= 1
line_insert(backlog)
elif char == input_code['^C']:
raise KeyboardInterrupt
elif char == input_code['^D']:
raise EOFError
elif char == input_code['^V']:
paste = get_clipboard_data()
backlog = response[position:]
response = response[:position] + paste + backlog
position += len(paste)
line_insert(backlog, extra=paste)
elif char == input_code['^Z']:
sigtstp()
elif char == input_code['enter']:
finalise_history(history_index, response, replacements,
input_replaced, history_modified)
move_cursor('right', len(response) - position)
return response
else:
backlog = response[position:]
response = response[:position] + char + backlog
position += 1
line_insert(backlog, extra=char)
def main():
"""Called if script isn't imported."""
# "print(text, end='')" is equivalent to "print text,", and 'flush'
# forces the text to appear, even if the line isn't terminated with
# a '\n'
print('Hello, ', end='', flush=True)
name = input_no_newline() # pylint: disable=unused-variable
print(', how do you do?')
if __name__ == '__main__':
main()
As you can see, it's a lot of work for not that much since you need to deal with the different operating systems and basically reimplement a built-in function in Python rather than C. I'd recommend that you just use the simpler TempHistory class I made in another answer, which leaves all the complicated logic-handling to the built-in function.
Like Nick K. said, you'll need to move the text cursor back to before the newline was echoed. The problem is that you can't easily get the length of the previous line in order to move rightward, lest you store every string printed, prompted and inputted in its own variable.
Below is a class (for Python 3) that fixes this by automatically storing the last line from the terminal (provided you use its methods). The benefit of this compared to using a terminal control library is that it'll work in the standard terminal for both the latest version of Windows as well as *NIX operating systems. It'll also print the 'Hello, ' prompt before getting input.
If you're on Windows but not v1511 of Windows 10, then you'll need to install the colorama module or else this won't work, since they brought ANSI cursor movement support in that version.
# For the sys.stdout file-like object
import sys
import platform
if platform.system() == 'Windows':
try:
import colorama
except ImportError:
import ctypes
kernel32 = ctypes.windll.kernel32
# Enable ANSI support on Windows 10 v1511
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
else:
colorama.init()
else:
# Fix Linux arrow key support in Python scripts
import readline
class TempHistory:
"""Record one line from the terminal.
It is necessary to keep track of the last line on the terminal so we
can move the text cursor rightward and upward back into the position
before the newline from the `input` function was echoed.
Note: I use the term 'echo' to refer to when text is
shown on the terminal but might not be written to `sys.stdout`.
"""
def __init__(self):
"""Initialise `line` and save the `print` and `input` functions.
`line` is initially set to '\n' so that the `record` method
doesn't raise an error about the string index being out of range.
"""
self.line = '\n'
self.builtin_print = print
self.builtin_input = input
def _record(self, text):
"""Append to `line` or overwrite it if it has ended."""
if text == '':
# You can't record nothing
return
# Take into account `text` being multiple lines
lines = text.split('\n')
if text[-1] == '\n':
last_line = lines[-2] + '\n'
# If `text` ended with a newline, then `text.split('\n')[-1]`
# would have merely returned the newline, and not the text
# preceding it
else:
last_line = lines[-1]
# Take into account return characters which overwrite the line
last_line = last_line.split('\r')[-1]
# `line` is considered ended if it ends with a newline character
if self.line[-1] == '\n':
self.line = last_line
else:
self.line += last_line
def _undo_newline(self):
"""Move text cursor back to its position before echoing newline.
ANSI escape sequence: `\x1b[{count}{command}`
`\x1b` is the escape code, and commands `A`, `B`, `C` and `D` are
for moving the text cursor up, down, forward and backward {count}
times respectively.
Thus, after having echoed a newline, the final statement tells
the terminal to move the text cursor forward to be inline with
the end of the previous line, and then move up into said line
(making it the current line again).
"""
line_length = len(self.line)
# Take into account (multiple) backspaces which would
# otherwise artificially increase `line_length`
for i, char in enumerate(self.line[1:]):
if char == '\b' and self.line[i-1] != '\b':
line_length -= 2
self.print('\x1b[{}C\x1b[1A'.format(line_length),
end='', flush=True, record=False)
def print(self, *args, sep=' ', end='\n', file=sys.stdout, flush=False,
record=True):
"""Print to `file` and record the printed text.
Other than recording the printed text, it behaves exactly like
the built-in `print` function.
"""
self.builtin_print(*args, sep=sep, end=end, file=file, flush=flush)
if record:
text = sep.join([str(arg) for arg in args]) + end
self._record(text)
def input(self, prompt='', newline=True, record=True):
"""Return one line of user input and record the echoed text.
Other than storing the echoed text and optionally stripping the
echoed newline, it behaves exactly like the built-in `input`
function.
"""
if prompt == '':
# Prevent arrow key overwriting previously printed text by
# ensuring the built-in `input` function's `prompt` argument
# isn't empty
prompt = ' \b'
response = self.builtin_input(prompt)
if record:
self._record(prompt)
self._record(response)
if not newline:
self._undo_newline()
return response
record = TempHistory()
# For convenience
print = record.print
input = record.input
print('Hello, ', end='', flush=True)
name = input(newline=False)
print(', how do you do?)
As already answered, we can't stop input() from writing a newline. Though it may not satisfy your expectation, somehow the following codes satisfy the condition if -
you don't have any issue clearing the screen
import os
name = input("Hello, ")
os.system("cls") # on linux or mac, use "clear"
print(f"Hello, {name}, how do you do?")
or no issue using the gui dialog box, as dialog box disappears after taking user input, you will see exactly what you expected
import easygui
name = easygui.enterbox("Hello, ", "User Name")
print("Hello, "+name+", how do you do?")
I think you can use this:
name = input("Hello , ")
It should be something like this:-
print('this eliminates the ', end=' ')
print('new line')
The output is this:-
this eliminates the new line.

Categories