在 python 中运行特定的批处理命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17120912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run a specific batch command in python
提问by user2072826
What if I want to include a single batch command that isn't already in a file in python?
如果我想在 python 的文件中包含一个尚未包含的批处理命令怎么办?
for instance:
例如:
REN *.TXT *.BAT
Could I put that in a python file somehow?
我可以把它放在一个python文件中吗?
回答by Endoro
try this:
尝试这个:
cmd /c ren *.txt *.bat
or
或者
cmd /c "ren *.txt *.bat"
回答by Sylvain Leroux
The "old school" answer was to use os.system. I'm not familiar with Windows but something like that would do the trick:
“老派”的答案是使用os.system. 我不熟悉 Windows,但类似的东西可以解决问题:
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.systemis subprocess.call
但是现在,正如 Ashwini Chaudhary 所注意到的,“推荐”的替代品os.system是subprocess.call
If RENis a Windows shell internalcommand:
如果REN是 Windows shell内部命令:
import subprocess
subprocess.call('ren *.txt *.bat', shell=True)
If it is an externalcommand:
如果是外部命令:
import subprocess
subprocess.call('ren *.txt *.bat')
回答by Sylvain Leroux
A example use subprocess for execute a command of Linux from Python:
使用子进程从 Python 执行 Linux 命令的示例:
mime = subprocess.Popen("/usr/bin/file -i " + sys.argv[1], shell=True, stdout=subprocess.PIPE).communicate()[0]
回答by AjV Jsy
I created a test.pycontaining this, and it worked....
我创建了一个test.py包含这个的,它工作了....
from subprocess import Popen # now we can reference Popen
process = Popen(['cmd.exe','/c ren *.txt *.tx2'])

