I am currently creating a command-based game using Python's cmd
module.
At a certain point, my cmd.Cmd
objects get nested. If I say that I am running the command prompt A
, at a certain point a new prompt B
is created inside A
. I want to, when my B
finishes, return a certain value to A
again. All my trials have just ended up with the inner command prompts returning None
. To try to understand this situation better I tried to simplify the question and just tried to get a return value from a cmd.Cmd
object. This is what I have:
import cmd
class Test(cmd.Cmd):
def __init__(self, value):
cmd.Cmd.__init__(self)
self.value = value
def do_bye(self, s):
return True
def postloop(self):
print("Entered the postloop!")
return self.value
And then at the shell I already tried:
a = Test("bla bla")
print(a.cmdloop())
# after the "bye" command it prints None
print(Test("bla bla").cmdloop())
# after the "bye" command it ALSO prints None
a = Test("safsfa").cmdloop()
print(a)
# Also prints None
I don't seem to be able to make the cmd.Cmd
object return any value. How can one do that, or is it impossible for some reason I don't know?
You can redefine cmdloop()
in your subclass to return a particular value, after calling the superclass's version of cmdloop()
:
class Test(cmd.Cmd):
# ...
def cmdloop(self):
cmd.Cmd.cmdloop(self)
return self.value