billinair
billinair

Reputation: 93

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

Upvotes: 0

Views: 1350

Answers (2)

Rohi
Rohi

Reputation: 814

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

Upvotes: 2

PKey
PKey

Reputation: 3841

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

Upvotes: 1

Related Questions