0

Here is a simple script using the Python cmd2 library.

import cmd2

class App(cmd2.Cmd):

  result = 0

  # Long computation
  def do_add3(self, arg):
    r = 3 + int(arg)
    print(r)
    self.result = r

  # Scripting
  def do_test(self, arg):
      self.do_add3("4")
      self.do_add3("2")
      self.do_add3("1")
      print(self.result)

if __name__ == '__main__':
  app = App()
  app.cmdloop()

Gist link

The result of a do_add3 function is saved (returned) into self.result. Later that do_add3 was called internally with self.do_add3("4").

Is there a better way to return results from a do_ function, such that I can code like in the following?

self.do_add("4") + self.do_add("3") + self.do_add("2")

P.S. For example, I can't use return inside do_ function to return value. Is there a better way?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zhe Hu
  • 3,777
  • 4
  • 32
  • 45
  • Please put all things needed to answer your question _inside_ it - that means: do not link to outside resources and dont post code /exceptions as pictures. – Patrick Artner Sep 05 '18 at 16:53
  • If you don't want to return inside you `do_` function then append the result to some global list inside your `do_` function and later after calling all the `do_` functions add the elements in the shared list? – Mohit Solanki Sep 05 '18 at 16:58
  • I'd like to be able to `return` inside `do_` function, but any `return` call would jump out of `cmd2`. So I am looking for a better way to return value from a `do_` function. – Zhe Hu Sep 05 '18 at 17:21

0 Answers0