How to run a routine continuously until input is entered in command line? - Python
Currently, I have a program that is designed to continuously send coordinates (encoded as ASCII) to a motor via socket communication, such that the motor moves with a sinusoidal motion. I would like for these coordinates to be continuously sent to the motor until the user enters end
into the command line.
I have this currently:
import socket
import numpy as np
import math
pi = math.pi
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP Server Connection
s1.connect(("192.168.177.200", 4001))
gearpositionlim = 10000
# sample sine
step = 2*pi / 2000
time_range = np.arange(0,2*pi + step,step)
x_motorrange = gearpositionlim*np.sin(time_range)
x_motorrange = ['la'+str(int(i)) for i in x_motorrange]
def motormove():
for i in np.arange(0,len(x_motorrange)):
s1.send(str(str(x_motorrange[i])+"\n").encode("ASCII"))
message = s1.recv(1024).decode()
#-------------------------------------------
while True:
motormove()
name = input("Code Running: Type 'end' to end program: ")
if name == 'end':
break
else:
print("ERROR: Home position not returned to")
exit()
#send the motor back to home position
s1.send("la0\n".encode("ASCII"))
s1.send("m\n".encode("ASCII"))
s1.send("np\n".encode("ASCII"))
s1.send("DI\n".encode("ASCII"))
However, the code currently only sends the coordinates x_motorrange
once, then gives the input prompt to type end
. Whereas, I would like for this prompt to always be present in the command line and for the routine motormove()
to only stop when the prompt end
is given. How can this be done?
insteade of writting exit
you can use KeyboardInterrupt
. so when you prees ctrl
+c
it will stop:
try:
while True:
do_something()
except KeyboardInterrupt:
pass