1

I'm trying to open the Windows command prompt using Python and then execute a few commands. This is the code I am using:

import os

os.system("start /B start cmd.exe @cmd /k cd C:/ & color 04")

Now the command prompt opens and the directory changes to just C:\> but the second command to change the color of the text doesn't work and no errors are produced. When I run cd C:/ & color 04 in the command prompt itself, it works though. So it seems my problem lies with the & sign in cd C:/ & color 4 since the command after the & does not execute.

How can I get this feature to work via my Python code (keep in mind I want the command prompt to be visible to the user)?

9
  • Could you use a minimal example of what isn't working the way you expect? E.g., does os.system("date & date") work or not? Commented Jun 2, 2017 at 5:45
  • I tried it now and it only executes once Commented Jun 2, 2017 at 5:48
  • ok. could you edit your question and add the more minimal example? Commented Jun 2, 2017 at 5:49
  • That's all the code I'm using, I can't make it more minimal than that unfortunately Commented Jun 2, 2017 at 5:50
  • i consider os.system("date & date") more minimal than os.system("start /B start cmd.exe @cmd /k cd C:/ & color 04"). the desired behavior in former case is much more obvious Commented Jun 2, 2017 at 5:52

1 Answer 1

6

Right syntax for such start command (typed in an open cmd window) is

start "" cmd /k "cd /D C:\ & color 04"

In Python, escape inner " (double quotes) and \ (reverse solidus) as follows:

import os
os.system("start \"\" cmd /k \"cd /D C:\\ & color 04\"")

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

Read also entire cmd /? and start /? for further explanation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.