[英]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? 如果我想在python中包含一个尚未存在于文件中的单个批处理命令,该怎么办?
for instance: 例如:
REN *.TXT *.BAT
Could I put that in a python file somehow? 我能以某种方式把它放在python文件中吗?
The "old school" answer was to use os.system
. “旧学校”的答案是使用os.system
。 I'm not familiar with Windows but something like that would do the trick: 我不熟悉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.system
is subprocess.call
但现在,通过阿什维尼乔杜里作为注意到,“推荐”的替代品os.system
是subprocess.call
If REN
is a Windows shell internal command: 如果REN
是Windows shell 内部命令:
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.... 我创建了一个包含这个的test.py
,它起作用....
from subprocess import Popen # now we can reference Popen
process = Popen(['cmd.exe','/c ren *.txt *.tx2'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.