使用python在批处理文件中运行命令 [英] use python to run commands in batch file

查看:78
本文介绍了使用python在批处理文件中运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python在批处理文件中运行命令.下面的屏幕截图显示了Windows cmd中的批处理文件和命令.

I want to use python to run commands in a batch file. The screen capture below shows the batch file and commands in Windows cmd.

我试图使用python打开批处理文件.

I tried to use python to open the batch file.

import os
os.system('C:/Program Files/MetroCon-3.2/RepSend/RepSendQXGA64.bat')

这将返回"1",表示失败.

This returns '1' which means failed.

import subprocess
filepath="C:/Program Files/MetroCon-3.2/RepSend/RepSendQXGA64.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
print (p.returncode)

此返回"0".命令列表在 stdout 中,并且可以在python中显示.

This return '0'. And the list of commands are in stdout and can be shown in python.

问题是,如何在Windows cmd中运行批处理文件中的特定命令.

The question is how to run the specific command in the batch file as it runs in Windows cmd.

推荐答案

如果要从bat文件中运行特定命令,则可以将bat文件作为txt文件打开(或使用stdout输出),请读取该行然后通过winpexpect模块与cmd通信.

If you want to run specific commands from the bat file, you could open the bat file as a txt file (Or use the stdout output), read it line by line and then communicate with the cmd via the winpexpect module.

import winpexpect
import subprocess
import multiprocessing
cmd = winpexpect.winspawn("cmd")
# Create read write buffers
cmd.logfile_read = read_buffer
cmd.logfile_write = write_buffer
cmd.sendline("insert whatever command line you want")

edit:如果我对您的理解正确,那么我可以添加读/写缓冲区标记

edit : If I understood you correctly, I could add the read/write buffer implemntation

这篇关于使用python在批处理文件中运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆