在python中运行特定的批处理命令

use*_*826 5 python module batch-file python-3.3

如果我想在python中包含一个尚未存在于文件中的单个批处理命令,该怎么办?

例如:

REN *.TXT *.BAT
Run Code Online (Sandbox Code Playgroud)

我能以某种方式把它放在python文件中吗?

Syl*_*oux 11

"旧学校"的答案是使用os.system.我不熟悉Windows,但这样的东西可以解决问题:

import os
os.system('ren *.txt *.bat')
Run Code Online (Sandbox Code Playgroud)

或者可能)

import os
os.system('cmd /c ren *.txt *.bat')
Run Code Online (Sandbox Code Playgroud)

但现在,正如Ashwini Chaudhary所注意到的那样,"推荐"的替代品os.systemsubprocess.call

如果REN是Windows shell 内部命令:

import subprocess
subprocess.call('ren *.txt *.bat', shell=True)
Run Code Online (Sandbox Code Playgroud)

如果是外部命令:

import subprocess
subprocess.call('ren *.txt *.bat')
Run Code Online (Sandbox Code Playgroud)


End*_*oro 1

尝试这个:

cmd /c ren *.txt *.bat
Run Code Online (Sandbox Code Playgroud)

或者

cmd /c "ren *.txt *.bat"
Run Code Online (Sandbox Code Playgroud)