I am trying to make a program that will pick a random number, and run a corresponding command to that number. I put multiple commands in a list as seen below
list = [cmd1(), cmd2(), cmd3(), cmd4()]
x = randint(0, len(list-1))
list[x]
Is there any way to run a command this way? (I am using python 3.5)
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!
Running a Command with subprocess In the first line, we import the subprocess module, which is part of the Python standard library. We then use the subprocess. run() function to execute the command.
If you need to execute a shell command with Python, there are two ways. You can either use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.
Yes, functions and methods are first class objects, you can assign them, pass them as arguments, etc...:
commands = [cmd1, cmd2, cmd3, cmd4] # omit the parenthesis (call)
current_command = random.choice(commands)
current_command()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With