我正在制作一个python程序来控制基本上读取先前生成的机器文件的机器人手臂,并通过TCP / IP在for循环读取线和基本开关结构中向机器人发送指令。
我在python的开头声明了一些参数,如:
speed_normal = 5 # mm/s
acc_normal = 1 # mm/s2
wait_time = 1000 # ms
然后我打开并阅读指令文件:
for index,filename in enumerate(glob.glob(os.path.join(directory, '*.moi')))
with open(filename) as f:
cmd_list = f.read().splitlines()
for cmd_line in cmd_list:
bits = cmd_line.split(';')
其中一个开关盒改变了机器人的速度:
elif bits[0] == 'sp':
print('Speed Instruction',bits[1])
if bits[1] == 0:
robot.setSpeed(speed_linear=speed_normal)
所以我的问题是,如何在程序执行期间更改变量speed_normal
,让我们说一个外部文件作为一种"控制面板&#34 ;?因此,如果在不停止程序的情况下,我想将其更改为20 mm / s?
谢谢!
答案 0 :(得分:1)
您需要选择一种格式将配置存储在磁盘上,然后定期重新读取配置文件。我会写一些容器对象来透明地处理所有这些:
import os
from datetime import datetime, timedelta
SENTINEL = object()
class DynamicConfiguration(object):
def __init__(self, filename):
self.filename = filename
self.attributes = {}
self.last_modification = 0
self.last_reload_attempt = datetime(1900, 1, 1)
def reload_file(self):
mtime = os.path.getmtime(self.filename)
if mtime <= self.last_modification:
return
self.last_modification = mtime
with open(self.filename, 'r'):
self.attributes = ... # somehow populate them
def get(self, key, default=SENTINEL):
if datetime.now() - self.last_reload_attempt >= timedelta(seconds=5):
self.reload_file()
self.last_reload_attempt = datetime.now()
if default is SENTINEL:
return self.attributes[key]
else:
return self.attributes.get(key, default)
然后,您可以像这样使用它:
config = DynamicConfiguration('configuration.something')
...
robot.setSpeed(speed_linear=config.get('speed_normal', 5))