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

Time:07-02

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 !

CodePudding user response:

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')

CodePudding user response:

Having tried to check into this, I don't think it is a python issue.

I tried doing this, from a command line, for comparison:

start cmd /k cd .. & cd ..

It did not work. Only the first "cd .." got executed.

So it seems "&" is not a successful way to chain commands with "cmd /k". I checked && and that did not work either.

After further looking into it, there is one suggested workaround I found at the below link, which involves using a single line to temporarily write a script and execute that script. (though I did not try it)

https://superuser.com/questions/62850/execute-multiple-commands-with-1-line-in-windows-commandline

  • Related