Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a .bat file using python code

I try to run a .bat file in Windows using Python script.

ask.bat file:

Application.exe work.xml 

I write Python code :

import os os.system("D:\xxx1\xxx2XMLnew\otr.bat ") 

Output: when try to run the file its just give a blink of the command prompt, and the work is not performing.

Note: I try with alternate slash also , but it is not working.

And I also want to save output of the file in another file.

Can anyone suggest how can I make the script runnable.

like image 695
Silver Avatar asked Mar 29 '11 07:03

Silver


People also ask

What is batch file in Python?

It consists of a series of commands to be executed by the command-line interpreter, stored in a plain text file. A batch file may contain any command the interpreter accepts interactively and use constructs that enable conditional branching and looping within the batch file, such as IF , FOR , and GOTO labels.

How do I run a bat file from anywhere?

The path where your bat file is placed should be appended to the PATH variable. In your example append "C:\;" in the value for Path environment variable. Then you can execute MyBatch. bat from anywhere on the command line.

How do you execute a command in python?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!


1 Answers

This has already been answered in detail on SO. Check out this thread, It should answer all your questions: Executing a subprocess fails

I've tried it myself with this code:

batchtest.py

from subprocess import Popen p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder") stdout, stderr = p.communicate() 

batch.bat

echo Hello World! pause 

I've got the batchtest.py example from the aforementioned thread.

like image 196
das_weezul Avatar answered Sep 22 '22 07:09

das_weezul