Home > OS >  Python command prompt executed the second command before executing the first command
Python command prompt executed the second command before executing the first command

Time:07-20

I wrote a python script where in one step it has to open the terminal 'cmd.exe' and then should change the directory and run a second command in the changed directory.

proc = os.system('start cmd /K "cd C:\\Users\\..\\emulator && [the command I want to execute in the changed directory]"')

When executing in IDLE Shell, the command is working as expected but when I run my .py python code, it ends up running the second command before the first command to change the directory, hence the second command fails.

Is there any way to solve this?

CodePudding user response:

By default the Windows start command does not wait for the specified command to finish, so it's possible for the other command you want to execute to (randomly) start before the current working directory has been changed. You can add a /wait argument to it (the start command) which should prevent that from happening.

CodePudding user response:

This doesn't answer the question of why that is happening. But, if you use the newer subprocess library, you can pass a working directory as a parameter:

subprocess.run('my command', cwd='C:\emulator')
  • Related