简体   繁体   中英

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?

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')

try this:

cmd /c ren *.txt *.bat

or

cmd /c "ren *.txt *.bat"

示例使用子进程从Python执行Linux命令:

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

I created a test.py containing this, and it worked....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM