use python to run commands in batch file

2019-08-19 06:22发布

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. screen capture

I tried to use python to open the batch file.

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

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)

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

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

2条回答
Summer. ? 凉城
2楼-- · 2019-08-19 07:05

Do you mean something like this?

import os
os.chdir("C:/Program Files/MetroCon-3.2/RepSend/")
os.startfile("RepSendQXGA64.bat")

or this?

os.system("start /wait cmd /c RepSendQXGA64.bat")
查看更多
欢心
3楼-- · 2019-08-19 07:09

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 : If I understood you correctly, I could add the read/write buffer implemntation

查看更多
登录 后发表回答