简体   繁体   中英

Python dynamically change a variable inside loop from exterior

I am making a python program to control robotic arms that basically reads a machine file previously generated and sends instructions to the robot via TCP/IP in a for loop reading lines and a basic switch structure.

I am declaring some parameters at the beginning of python like:

speed_normal = 5 # mm/s
acc_normal = 1 # mm/s2
wait_time = 1000 # ms

Then I open and read the instruction file:

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(';')

One of the switch cases changes the speed of the robot:

        elif bits[0] == 'sp':
            print('Speed Instruction',bits[1])

            if bits[1] == 0:

                robot.setSpeed(speed_linear=speed_normal)

So my question is, how could I change the variable speed_normal during the execution of the program, let's say from an external file that works as a sort of "control panel"? So if, without stopping the program, I would like to change it to 20 mm/s?

Thanks!

You need to pick a format for storing the configuration on disk and then re-read the configuration file periodically. I would write some sort of container object to handle all of this transparently:

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)

Then, you can just use it like this:

config = DynamicConfiguration('configuration.something')

...

robot.setSpeed(speed_linear=config.get('speed_normal', 5))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM