Sang-il Ahn
Sang-il Ahn

Reputation: 103

open and write commands in command prompt from subprocess.Popen python in Windows 10

I want to write python script to run a program in command prompt in Windows 10 (64 bit).

My current working directory is 'C:\Python\Project'. My target is to change this working directory to 'D:\Calculation' and to view the content of the files by typing in 'dir'. I've searched and looked through the official documents but I can't find how I can do this.

This works well:

subprocess.Popen(['start', 'cmd', '/k', 'cd /d d:\Calculation'], shell = True)

However, that doesn't work:

subprocess.Popen(['start', 'cmd', '/k', 'cd /d d:\Calculation', '&', 'dir'], shell = True)

But this works (I can see both command prompt (its location successfully changed to 'd:\Calculation' and the notepad application opened):

subprocess.Popen(['start', 'cmd', '/k', 'cd /d d:\Calculation', '&', 'notepad.exe'], shell = True)

Any ideas to solve this?

Upvotes: 1

Views: 1906

Answers (1)

thuhbruhuhh
thuhbruhuhh

Reputation: 50

In case anyone else has a similar problem, this code should work:

subprocess.Popen(['start', 'cmd', '/k', 'cd /d d:\Calculation & dir'], shell = True)

The trick is to include the '&' stuff with the command.

Upvotes: 3

Related Questions