3

I'm creating instrument classes for use with pyvisa. Rather than manually convert every SCPI command (about 400) into methods, I'd like to just copy the command quick reference into a text file and have commands like this:

[SENSe:]TEMPerature:TRANsducer:RTD:RESistance[:REFerence]? [{MIN|MAX}]

Wind up as methods like this:

def temp_tran_rtd_res_qry(*args):
 <check for valid arguments>
 cmd = 'TEMPerature:TRANsducer:RTD:RESistance?'
 argstr = ''
 for arg in args:
 argstr += ' ' + arg
 return self.query(cmd + argstr)

I have a handle on parsing the commands, and I figured out how to use setattr() to create the methods with the correct names from a template function.

The part that's giving me trouble is where each method knows what to assign to cmd. I thought I might add the original strings to the class as attributes (named similar to the methods) and parse them on the fly in the methods, but for this, the methods to be able to retrieve class attributes based on their names (or something).

asked Feb 20, 2017 at 6:00
2
  • Possible duplicate of How can I dynamically create class methods for a class in python Commented Feb 20, 2017 at 6:07
  • That's the answer I found to get as far as I did. There's a bit more to my problem than just the method creation. Maybe my question isn't specific enough. Commented Feb 20, 2017 at 6:11

1 Answer 1

1

So, here's what I figured out:

>>> class A(object):
 pass
>>> a = A()
>>> a. # Only default 'object' methods avaliable
>>> cmdstr = '[SENSe:]VOLTage[:DC]:RANGe[:UPPer] {<range>|MIN|MAX|DEF} '
>>> querystr = """def query(cls, *args): cmd = '{s}'; return command_handler(*args, cmdstr=cmd)"""
>>> exec(querystr.format(s=cmdstr))
>>> setattr(A, command_name(command_abridge(cmdstr)), classmethod(query))
>>> a.volt_rang() # Autocomplete works
<results from command_handler()>

I can write a file parser into __init__ to add a method to the class for each command string in a text file and I can write a generic method to parse the arguments and build the command strings for the actual queries.

answered Feb 21, 2017 at 15:32
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.