Run a specific command command in python

What if I want to include one command command that is not already in the file in python?

eg:

REN *.TXT *.BAT 

Can I somehow put this in a python file?

+4
source share
4 answers

The answer of the "old school" was to use os.system . I am not familiar with Windows, but something like this will do the trick:

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

Or (maybe)

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

But now, as Ashvini Chodhari noted, the "recommended" replacement is os.system subprocess.call

If REN is an internal Windows shell command:

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

If this is an external command:

 import subprocess subprocess.call('ren *.txt *.bat') 
+10
source

try the following:

 cmd /c ren *.txt *.bat 

or

 cmd /c "ren *.txt *.bat" 
+1
source

In the example, use the subprocess to execute the Linux command from Python:

 mime = subprocess.Popen("/usr/bin/file -i " + sys.argv[1], shell=True, stdout=subprocess.PIPE).communicate()[0] 
+1
source

I created test.py containing this and it worked.

 from subprocess import Popen # now we can reference Popen process = Popen(['cmd.exe','/c ren *.txt *.tx2']) 
+1
source

Source: https://habr.com/ru/post/1486360/


All Articles