How to process syntax errors

Terry Reedy tjreedy at udel.edu
Wed Oct 12 17:28:48 EDT 2016


On 10/12/2016 5:59 AM, mr.puneet.goyal at gmail.com wrote:

> # I created a platform class with different method in a file
 > # and making it as a package.
> class platform:
>     def connect(self):
>         # connect device
>     def destroy(self):
>         # destroy device
>     def config(self, command):
>         # Send command to configure device
>     def show(self, command):
>         # check device health

> Now person who wants to write a script using above package can simply
 > use below approach. Which does not make him to have knowledge in python.
>
> DUT = platform()
> DUT connect
> DUT config {commands}
> DUT show {commands}
> DUT destroy

> But I know this is not easy to do in python.

Actually, as long as args (commands) continue to be space separated, it 
is. One way would be to add the following after the class statement.

def execute(file):
     with open(file) as f:
         ns = {}
         for line in f:
              if '=' in line:
                  exec(line, ns)
              else:
                  fields = line.split()
                  exec('%s.%s(*%s)' %
                       (fields[0], fields[1], fields[2:]), nd)

if __name__ = __main__:
     import sys
     execute(sys.argv[1])
--
If the module is platform.py, then the command line usage would be
 > platform <script>

To test, temporarily put print('connect'), etc, in each method.

If only one platform instance can exist at a time, then users need not 
name it and repeatedly use it.

-- 
Terry Jan Reedy




More information about the Python-list mailing list