简体   繁体   中英

use python to run commands in batch file

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. 屏幕截图

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.

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM