Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a specific batch command in python

What if I want to include a single batch command that isn't already in a file in python?

for instance:

REN *.TXT *.BAT

Could I put that in a python file somehow?

like image 912
user2072826 Avatar asked Jun 15 '13 06:06

user2072826


People also ask

How do you execute a command in python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


2 Answers

The "old school" answer was to use os.system. I'm not familiar with Windows but something like that would do the trick:

import os
os.system('ren *.txt *.bat')

Or (maybe)

import os
os.system('cmd /c ren *.txt *.bat')

But now, as noticed by Ashwini Chaudhary, the "recommended" replacement for os.system is subprocess.call

If REN is a Windows shell internal command:

import subprocess
subprocess.call('ren *.txt *.bat', shell=True)

If it is an external command:

import subprocess
subprocess.call('ren *.txt *.bat')
like image 54
Sylvain Leroux Avatar answered Sep 28 '22 06:09

Sylvain Leroux


try this:

cmd /c ren *.txt *.bat

or

cmd /c "ren *.txt *.bat"
like image 45
Endoro Avatar answered Sep 28 '22 05:09

Endoro