How can i run multiple commands in python script

时间:2019-04-08 12:59:27

标签: python-3.x subprocess ncurses

How can i run multiple commands using python script

I have already written following code, but still is there any other alternative?

 os.system("clear")
 os.system("virtualenv -p python3 /opt/"+name)
 os.system("source /opt/"+name+"/bin/activate")
 os.system("pip install /usr/share/my-packages/*")

Also please let me know if there is any way that can do one of following: -Either don't on console what is happening with commands such as: creating virtual envirnoment. etc. -Or else those statements which are going to be printed on console any how i can get it in any variable so that i can use those on python-curses.

2 个答案:

答案 0 :(得分:1)

Problem 1

How can i run multiple commands using python script

To run multiple commands, you can use the & to separate the command:

os.system("clear & "
          "virtualenv -p python3 /opt/" + name + " & "
          "source /opt/" + name + "/bin/activate" + " & "
          "pip install /usr/share/my-packages/*")

Problem 2

Either don't on console what is happening with commands such as: creating virtual envirnoment. etc.

If you don't want the comman result to be displayed on the console, you can add > nul to the end of the command line.

xcopy /s c:\source d:\target > nul

答案 1 :(得分:1)

Try building a list:

commands = ['clear', 
            'virtualenv -p python3 /opt/'+name, 
            'source /opt/'+name+'/bin/activate',
            'pip install /usr/share/my-packages/*']

for command in commands:
    os.system(command)

This allows for easier maintenance of the commands you want to include/exclude.