How can we interact with OS shell using Python ? I want to run windows cmd commands via python. How can it be achieved ?
This question is related to
python
windows
operating-system
shell
You can use the subprocess
package with the code as below:
import subprocess
cmdCommand = "python test.py" #specify your cmd command
process = subprocess.Popen(cmdCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
print output
Simple Import os package and run below command.
import os
os.system("python test.py")
Refactoring of @srini-beerge's answer which gets the output and the return code
import subprocess
def run_win_cmd(cmd):
result = []
process = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for line in process.stdout:
result.append(line)
errcode = process.returncode
for line in result:
print(line)
if errcode is not None:
raise Exception('cmd %s failed, see above for details', cmd)
import subprocess
result = []
win_cmd = 'ipconfig'(curr_user,filename,ip_address)
process = subprocess.Popen(win_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE )
for line in process.stdout:
print line
result.append(line)
errcode = process.returncode
for line in result:
print line
You would use the os module system method.
You just put in the string form of the command, the return value is the windows enrivonment variable COMSPEC
For example:
os.system('python') opens up the windows command prompt and runs the python interpreter
Source: Stackoverflow.com