Requesting input from the user is straight forward, however we've included the shell.Prompt utility to expand beyond just a simple one-dimensional input response.
example.py
from cement import shell### simple user response promptp = shell.Prompt("Press Enter To Continue", default='ENTER')res = p.prompt()### provide a numbered list for longer selectionsp = shell.Prompt("Where do you live?", options=['San Antonio, TX','Austin, TX','Dallas, TX','Houston, TX', ], numbered =True)res = p.prompt()### Create a more complex prompt, and process the inputclassMyPrompt(shell.Prompt):classMeta: text ="Do you agree to the terms?" options = ['Yes','no','maybe-so'] options_separator ='|' default ='no' clear =True max_attempts =99defprocess_input(self):if self.input.lower()=='yes':# do something crazypasselse:# don't do anything... maybe exit?print("User doesn't agree! I'm outa here")p =MyPrompt()
$ python example.py
### simple user response prompt
Press Enter To Continue
### provide a numbered list for longer selections
Where do you live?
1: San Antonio, TX
2: Austin, TX
3: Dallas, TX
4: Houston, TX
Enter the number for your selection: 1
### Create a more complex prompt, and process the input
Do you agree to the terms? [Yes|no|maybe-so] no
User doesn't agree! I'm outa here
Executing Commands
Shell commands can be executed via the shell.cmd() function in two ways; by capturing STDOUT/STDERR and exit code, or just the exit code and letting STDOUT/STDERR print to console normally.
from cement import shell### execute command and capture outputout, err, code = shell.cmd('echo helloworld')### execute command with output to consolecode = shell.cmd('echo helloworld', capture=False)
Spawning Processes and Threads
Spawning processes and threads is easy via the shell.spawn() helper.
from cement import shelldefadd(a,b):print(a + b)### spawn a processp = shell.spawn(add, args=(12, 27))p.join()### spawn a threadt = shell.spawn(add, args=(12, 27), thread=True)t.join()
See the multiprocessing and threading modules in the Python standard library for more information on working with processes and threads.