Search code examples
pythonpython-3.xpython-2.7cmdpython-os

Open cmd with Python Os.system and run commands inside the new opened cmd


I need to click in a button to call a python function (i did this), but now : I need a python script to open a new cmd, and in the opened cmd i want to do 2 commands : Cd and run a python file This code is the best thing i could do but it's not running the script !

import os
    username = os.getlogin()
    os.system('start cmd /k ; cd C:\\Users\\' + username + '\\Desktop\\Automatisation & python serverSender.py')

To resume : Start cmd /k (Open new cmd and remain) cd C:\Users\' + username + '\Desktop\Automatisation (To change directory) python serverSender.py (To run the python script inside Automatisation directory)

But the last command : python serverSender.py is not executing ! As you can see in the screen, the function opens a new cmd when i click on the button , it's goes to the directory in the cd command, but it's not starting the serverSender.py file ! Cmd Opened

Any idea on how to run the third command ? (i don't want to run it in another cmd, i want to run it in the opened cmd with the first command ) Thanks !


Solution

  • The & is interpreted by the outer shell and not the one inside start. You need to escape it, by changing & to ^&:

    os.system('start cmd /k ; cd C:\\Users\\' + username + '\\Desktop\\Automatisation ^& python serverSender.py')