Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run a command that is in a list?

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)

like image 901
Piguinrulist Avatar asked Apr 26 '16 14:04

Piguinrulist


People also ask

How do you execute a command line in Python?

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!

How do you run a subprocess command in Python?

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.

How do I run a .sh file in Python?

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.


1 Answers

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()
like image 99
Reblochon Masque Avatar answered Sep 19 '22 16:09

Reblochon Masque