'Can I tell Python to execute command line in cmd?

I'm working on a personal project as a very amateur programmer and to do this, I need to have python tell cmd to run an external program via command line.

For example, I need to chdir ("C:\blah\blah") on Python, and run externalprogram -w "<destination>\newName.fileType>" "<source>\*.*".

I'm very lost in how to do this and any help would be greatly appreciated.

So far my code looks like this

import os

os.chdir('C:\Program Files (x86)\<externalProgram>')
os.system('<externalCommand> "<destination>\file.fileType" "<source>\*.*"')

Still can't get it to work though no errors are being posted to the shell.



Solution 1:[1]

The simplest way to do it is:

import os
os.system('your command')

Solution 2:[2]

Yes. You need the os.system() method, near the bottom of this page. You pass the command you want to run as a string.

Also, many UNIX system commands are built into this package; you might find the one you want as a specific call.

Solution 3:[3]

Your quotation marks?

os.system('<command> "<destination>\file.fileType" "<source>\*.*") #still in quote

starts with ' ends in "

os.system('<command> "<destination>\file.fileType" "<source>\*.*" ') #closed properly

If you don't want quotations in python to be recognised in quotes put a backslash in front

print (" \" ") # prints out "

say add parameters to the command

destination = "folder\file.fileType"
source = "source\*.*"
os.system('<command> \" ' + destination + ' \" '+ source+' \" ') #closed 

Solution 4:[4]

So, my main issues were not adding the /D when for my directory change to change the disk as well, and the use of the '&&'.

import os
changeDir = ('cd /D C:\\Program Files (x86)\\externalProgram')
externalCommand = '<Command> \"<destination>\\newName.fileType\" \"<source>\\*.*\"'
os.system(changeDir + ' && ' externalCommand)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yevhen Kuzmovych
Solution 2 Prune
Solution 3 Fishtallen
Solution 4 halfer