[Twisted-Python] How to use AmpList?

Peter Westlake peter.westlake at pobox.com
Mon Mar 29 07:51:33 MDT 2010



On Mon, 29 Mar 2010 14:54 +0300, "Vlad Shevchenko"
<vlad.shevchenko at gmail.com> wrote:
> No one use AmpList?
> 
> On Sat, Mar 27, 2010 at 11:45 PM, Vlad Shevchenko
> <vlad.shevchenko at gmail.com
> > wrote:
> 
> > Hi,
> > can't find any reference of how to use AmpList. What should be passed to
> > callRemote? In command: arguments = Amp.List(...) or arguments = [('param',
> > AmpList(...))]? Responder params?
> >
> > Please, advice some refs or examples.

Here's an example. I've missed out the other arguments for clarity. The
data being passed is a Unix-style environment string. It needs to be
reformatted to make it suitable for passing in an AmpList, but that's
just an implementation detail. It's because the AmpList requires the
dictionary keys to be declared in advance, but I want to be able to pass
environment variables whose names are only known at run-time. Your code
might not need to do any of that.

First, the command:

  class RunCmd(amp.Command):
      arguments = [...,
                   ('env',  amp.AmpList([('var', amp.String()), ('val',
                   amp.String())])),
                   ...]


Then the call:

          # env is something like {'PATH': '/bin:/usr/bin', 'HOME':
          '/home/peter'}
          # It needs to be converted into a form suitable for AmpList,
          like this:
          # [{'var': 'PATH', 'val': '/bin:/usr/bin'}, {'var': 'HOME',
          'val': '/home/peter'}]
          #
          amp_env  = [{'var': var, 'val': val} for (var, val) in
          env.items()]
          d = self.protocol.callRemote(commands.RunCmd, ...,
          env=amp_env, ...)


Then the responder:

    def runcmd(..., env, ..):
        """Implementation of the AMP command RunCmd.
        ...
        """

        # The "env" argument represents the environment of a process.
        # Convert it from the AmpList format back to a Python
        dictionary.
        #
        envd = {}
        for var in env:
            envd[var['var']] = var['val']
        ...
        return {...}
    
    commands.RunCmd.responder(runcmd)


Peter.




More information about the Twisted-Python mailing list