Trying to make a program that simulates typing - python

I'm trying to making a program where each keypress prints the next character in a predetermined string, so it's like the user is typing text.
Here's the code I'm trying to use:
def typing(x):
letter = 0
for i in range(0, len(x)):
getch.getch()
print(x[letter], end = "")
letter += 1
typing("String")
What happens here is you need to press 6 keys (The length of the string) and then it prints all at once. I can sort of fix this by removing the , end = "", which makes the letters appear one at a time, but then the outcome looks like this:
S
t
r
i
n
g
Any ideas for making the letters appear one at a time and stay on the same line?

You can try this code which works for me:
import time
def typewrite(word: str):
for i in word:
time.sleep(0.1)
print(i, end="", flush = True)
typewrite("Hello World")

Related

Python Label Printer Program

I want to print two labels that have the same numbers on them. I am using ZPL. I have already made my print format in ZPL and it works properly. I am trying to print a data range. For example:
"What is the first number in the range?" User inputs 100
"What is the second number in the range?" User inputs 120
I would then get 40 labels in order.
I then want it to export that data into a notepad file and then print it to my default printer. My problem is that to print with ZPL I have to "tag" my data range with my ZPL code. I cant figure out how to get my data range to go into my print statement correctly. Please help. Thank you in advance!
import os
import sys
start = int(input("Enter the start of range: "))
end = int(input("Enter the end of range: "))
with open('TestFile.txt', 'a') as sys.stdout:
print('^XA')
print('^PQ2')
for labelRange in range(start, end + 1):
print('^FO185,50^A0,300^FD')(labelRange, end = " ")('^FS')
#print('\n')
print('^XZ')
os.startfile("C:/Users/joe.smith/desktop/TestFile.txt", "print")
exit()
here is something to get you started, but I doubt it is complete. You will need to provide a valid ZPL file for making the changes.
I also made the program use fixed numbers for now and so it just runs and outputs.You can change it back once you have it working.
start = 110
end = 111
notepad = ''
# these are header lines that go once (if windows you might need \r\n instead of \n)
notepad += '^XA\n'
notepad += '^PQ2\n'
for label in range(start, end + 1):
# use f-strings
notepad += f'^FO185,50^A0,300^FD{label}^FS\n'
# if you need some of those other numbers to increment
# then setup a counter and do the math here inside the f-string
notepad += f'^FO185,50^A0,300^FD{label}^FS\n'
notepad += '^XZ\n'
# with open('tf.txt', 'w') as sys.stdout:
# print(notepad)
print(notepad)
exit()
outputs:
^XA
^PQ2
^FO185,50^A0,300^FD110^FS
^FO185,50^A0,300^FD110^FS
^FO185,50^A0,300^FD111^FS
^FO185,50^A0,300^FD111^FS
^XZ

How can I get pyautogui to print words from a string?

I'm working on a project which I want to be able to take words separated by a space, turn it into a string using .split() and then have pyautogui print it out with an "enter" being pressed in between each word. This is the code I have so far below.
# Importing stuff
import pyautogui
# Configure Typing Thing
pyautogui.PAUSE = 0
# Input
input = "hi this is a test run of this program"
# generate words
output_list = input.split()
pyautogui.write(output_list)
pyautogui.press("enter")
Could someone tell me what I did wrong while writing this? Thanks in advance.
Try this:
import pyautogui
pyautogui.PAUSE = 0
input = "hi this is a test run of this program"
output_list = input.split()
for x in output_list:
pyautogui.write(x)
pyautogui.press("enter")
You probably should not use the word input as a variable name as it is a builtin function in Python. To print the words with an enter between them use the following code:
ipt = "hi this is a test run of this program"
ipt = ipt.split()
for word in ipt:
pyautogui.write(word + "\n")
The "\n" is interpreted as a new line character and therefore the write function prints it as a new line (aka an enter)
EDIT: Even easier is something where you replace every space in the string with a newline character and then write that. For example:
ipt = "hi this is a test run of this program"
ipt = ipt.replace(" ", "\n")
pyautogui.write(ipt)

Splice a string, multiple times, using a keyword

I am trying to break a string apart by removing segments that occur between two words.
Example:
AGCGUGUGAGAGCUCCGA
I will remove the parts that occur between: GUGU and AGAG
So, the new string will be:
AGCCUCCGA
I wrote a code that utilises while loop to keep 'splicing' a string over and over till it can't find the GUGU and AGAG in the string. The process works, most of the time.
I encountered one case where the 'input' is extremely long and then my code is stuck in an infinite loop and I don't understand why that is the case.
I was hoping that someone could review it and help me improve on what I am doing.
def splice(strand):
while True:
initial = strand.find('GUGU')
final = strand.find('AGAG')
if initial == -1:
break
if final == -1:
break
strand = strand[:initial] + strand[final+4:]
return strand
if __name__ == "__main__":
strand = input("Input strand: ")
print()
spliced = splice(strand)
print("Output is {}".format(spliced))
The case where it is failing is:
GUGUAGAGGUCACAGUGUAAAAGCUCUAGAGCAGACAGAUGUAGAGGUGUUGUGUAACCCGUAGAGCAAAGGCAACAGUGUGUAAAGAGGUGUAAAGAG
Expected result:
GUCACACAGACAGAUGUAGAGCAAAGGCAACA
I haven't encountered any other cases where the code will not work.
Your code doesn't work if AGAG is right before GUGU. After the first iteration on that input, the value of strand is
GUCACACAGACAGAUGUAGAGGUGUUGUGUAACCCGUAGAGCAAAGGCAACAGUGUGUAAAGAGGUGUAAAGAG
Then initial is 21 and final is 17, so you do:
strand = strand[:21] + strand[21:]
which just sets strand back to the same value, so you get stuck in a loop.
The string.find() method has an optional start argument, so you can tell it to start looking for AGAG after initial:
final = strand.find("AGAG", initial+4)
You can also do the whole thing with a regexp substitution:
import re
strand = re.sub(r'GUGU(.*?)AGAG', '', strand)
import re
pattern = '(.*?)GUGU.*?AGAG'
s1 = 'AGCGUGUGAGAGCUCCGA'
s2 = 'GUGUAGAGGUCACAGUGUAAAAGCUCUAGAGCAGACAGAUGUAGAGGUGUUGUGUAACCCGUAGAGCAAAGGCAACAGUGUGUAAAGAGGUGUAAAGAG'
print ''.join(re.findall(pattern,s1)) + s1[s1.rfind('AGAG')+4:]
print ''.join(re.findall(pattern,s2)) + s2[s2.rfind('AGAG')+4:]
AGCCUCCGA
GUCACACAGACAGAUGUAGAGCAAAGGCAACA

Stdout looping halt after certain amount of characters

I want my program to have a looping display, which the code works, but the problem is that the character display is a long continuous line whereas I want it to go back to the start of the printing after a certain amount of characters have been displayed.
This is the entire code at this current moment:
import time
import sys
def Startup(s):
for c in s:
sys.stdout.write( '%s' % c )
sys.stdout.flush()
time.sleep(0.25)
def StartUpDot(s):
while True:
timeout = time.time() + 3*5
Time = 0
for c in s:
sys.stdout.write( '%s' % c)
sys.stdout.flush()
time.sleep(0.25)
if Time == 5 or time.time() > timeout:
break
Time = Time - 1
Startup("BOOTING UP"),
StartUpDot(".......") #This is what i want to repeat
The function that I want to do what I ask is the StartUpDot function. It instead displays a continuous line like "BOOTING UP................. etc"
To clarify I want the ...... to repeat from the start, the "BOOTING UP" is from a different function, i put the comma there to make it one line. I have it in a loop if that helps.
Sorry about the confusion
You have two options:
If you want the text to print out on the line below the current text, you need to print a newline character to stdout
sys.stdout.write('\n')
If you're using a maximum line width of 10 characters your output will look like this:
1 BOOTING UP
2 ........
If you want to clear the current text and print on the same line, you need to print a carriage return to stdout, which returns the cursor to the front of the line. Then print empty space characters for the entire width of your line (to clear the old text), then another carriage return to return the cursor to the beginning of the line.
line_width = 10
sys.stdout.write('\r{0}\r'.format(' ' * line_width))
Using this method, the output would look like this (the line number is the same each time, so this is more like a time sequence).
1 BOOTING UP
1 OOTING UP.
1 OTING UP..
Here is an example
line_width = 10
for i in range(20):
msg = 'BOOTING{0}'.format('.' * i)
# Get only the last portion of the message
# that is shorter than the line width
msg = msg[-line_width:]
# Pad with spaces if shorter than line width
# Ensures old content is overwritten
msg = msg.ljust(line_width)
sys.stdout.write('\r{0}'.format(msg))

String to integer implicit change when not called for?

I'm trying to create a simple encryption/decryption code in Python like this (maybe you can see what I'm going for):
def encrypt():
import random
input1 = input('Write Text: ')
input1 = input1.lower()
key = random.randint(10,73)
output = []
for character in input1:
number = ord(character) - 96
number = number + key
output.append(number)
output.insert(0,key)
print (''.join(map(str, output)))
def decrypt():
text = input ('What to decrypt?')
key = int(text[0:2])
text = text[2:]
n=2
text = text
text = [text[i:i+n] for i in range(0, len(text), n)]
text = map(int,text)
text = [x - key for x in text]
text = ''.join(map(str,text))
text = int(text)
print (text)
for character in str(text):
output = []
character = int((character+96))
number = str(chr(character))
output.append(number)
print (''.join(map(str, output)))
When I run the decryptor with the output from the encryption output, I get "TypeError: Can't convert 'int' object to str implicitly."
As you can see, I've added some redundancies to help try to fix things but nothing's working. I ran it with different code (can't remember what), but all that one kept outputting was something like "generatorobject at ."
I'm really lost and I could use some pointers guys, please and thank you.
EDIT: The problem arises on line 27.
EDIT 2: Replaced "character = int((character+96))" with "character = int(character)+96", now the problem is that it only prints (and as I can only assume) only appends the last letter of the decrypted message.
EDIT 2 SOLVED: output = [] was in the for loop, thus resetting it every time. Problem solved, thank you everyone!
Full traceback would help, but it looks like character = int(character)+96 is what you want on line 27.

Categories