如何连续 运行 一个例程,直到在命令行中输入输入? - Python
How to run a routine continuously until input is entered in command line? - Python
目前,我有一个程序旨在通过套接字通信向电机连续发送坐标(编码为ASCII),以便电机以正弦运动运动。我希望将这些坐标连续发送到电机,直到用户在命令行中输入 end
。
我目前有这个:
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"))
但是,代码目前只发送一次坐标x_motorrange
,然后给出输入提示输入end
。然而,我希望此提示始终出现在命令行中,并且例程 motormove()
仅在给出提示 end
时停止。这怎么能做到?
您可以使用 KeyboardInterrupt
而不是 exit
。所以当你按下 ctrl
+c
时它会停止:
try:
while True:
do_something()
except KeyboardInterrupt:
pass
有很多方法可以解决这个问题:
例如,将一段代码移动到另一个线程或进程
import threading
import socket
import time
import numpy as np
import math
class MotoMover(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
pi = math.pi
self.id = 0
self.s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP Server Connection
self.s1.connect(("192.168.177.200", 4001))
gearpositionlim = 10000
# sample sine
step = 2 * pi / 2000
time_range = np.arange(0, 2 * pi + step, step)
self.x_motorrange = gearpositionlim * np.sin(time_range)
self.x_motorrange = ['la' + str(int(i)) for i in self.x_motorrange]
self.connected = False
self.stopped = False
def try_to_connect(self):
try:
self.s1.settimeout(1000)
self.s1.connect(("192.168.177.200", 4001), timeout=1000)
self.connected = True
except:
self.connected = False
def motormove(self):
for i in np.arange(0, len(self.x_motorrange)):
self.s1.send(str(str(self.x_motorrange[i]) + "\n").encode("ASCII"))
message = self.s1.recv(1024).decode()
def run(self): ## main cycle of the thread
while not self.stopped:
if not self.connected:
# print('connecting to server...')
self.try_to_connect()
else:
self.id += 1
self.motormove()
time.sleep(1) #pause = 1 sec. you can reduce it to a few ms (0.01, for example), but I do not recommend removing it completely
def stop(self):
self.stopped = True
def main():
moto = MotoMover()
moto.start()
while True:
name = input("Code Running: Type 'end' to end program: ")
if name.startswith('end'):
print("end of the program")
moto.stop()
moto.join()
exit(0)
else:
print('!', name)
if len(name) >= 3:
name = ''
main()
目前,我有一个程序旨在通过套接字通信向电机连续发送坐标(编码为ASCII),以便电机以正弦运动运动。我希望将这些坐标连续发送到电机,直到用户在命令行中输入 end
。
我目前有这个:
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"))
但是,代码目前只发送一次坐标x_motorrange
,然后给出输入提示输入end
。然而,我希望此提示始终出现在命令行中,并且例程 motormove()
仅在给出提示 end
时停止。这怎么能做到?
您可以使用 KeyboardInterrupt
而不是 exit
。所以当你按下 ctrl
+c
时它会停止:
try:
while True:
do_something()
except KeyboardInterrupt:
pass
有很多方法可以解决这个问题:
例如,将一段代码移动到另一个线程或进程
import threading
import socket
import time
import numpy as np
import math
class MotoMover(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
pi = math.pi
self.id = 0
self.s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # TCP Server Connection
self.s1.connect(("192.168.177.200", 4001))
gearpositionlim = 10000
# sample sine
step = 2 * pi / 2000
time_range = np.arange(0, 2 * pi + step, step)
self.x_motorrange = gearpositionlim * np.sin(time_range)
self.x_motorrange = ['la' + str(int(i)) for i in self.x_motorrange]
self.connected = False
self.stopped = False
def try_to_connect(self):
try:
self.s1.settimeout(1000)
self.s1.connect(("192.168.177.200", 4001), timeout=1000)
self.connected = True
except:
self.connected = False
def motormove(self):
for i in np.arange(0, len(self.x_motorrange)):
self.s1.send(str(str(self.x_motorrange[i]) + "\n").encode("ASCII"))
message = self.s1.recv(1024).decode()
def run(self): ## main cycle of the thread
while not self.stopped:
if not self.connected:
# print('connecting to server...')
self.try_to_connect()
else:
self.id += 1
self.motormove()
time.sleep(1) #pause = 1 sec. you can reduce it to a few ms (0.01, for example), but I do not recommend removing it completely
def stop(self):
self.stopped = True
def main():
moto = MotoMover()
moto.start()
while True:
name = input("Code Running: Type 'end' to end program: ")
if name.startswith('end'):
print("end of the program")
moto.stop()
moto.join()
exit(0)
else:
print('!', name)
if len(name) >= 3:
name = ''
main()