Run .bat file using Python - python

I have a batch file, which I use to load some pre-build binaries to control my device.
It's command is:
cd build
java -classpath .;..\Library\mfz-rxtx-2.2-20081207-win-x86\RXTXcomm.jar -
Djava.library.path=..\Library\mfz-rxtx-2.2-20081207-win-x86 tabotSample/Good1
pause
Now, I want to run the batch file using Python, and I tried os.system(batch,bat), and I tried using Popen
import os
from subprocess import Popen
os.popen("cd TAbot")
r=os.popen("hello.bat")
However, the python console(Anaconda python 2.7) seems like executed the code, but returns nothing, and nothing happens.
I want to run this batch file from python, please help me.
by the way, I tried popen for another batch file like,
echo Hello but nothing happens.

Here is the simple solution.
from subprocess import Popen
import subprocess
def run_batch_file(file_path):
Popen(file_path,creationflags=subprocess.CREATE_NEW_CONSOLE)
run_batch_file('file_name.bat')
file_name.bat
echo .bat file running from python
pause

You can also use this
import subprocess
subprocess.call(["C:\\temp\\test.bat"], shell=False)
test.bat
copy "C:\temp\test.txt" "C:\temp\test2.txt"

I think this should work like this:
batch.py
from subprocess import Popen
p = Popen("test.bat", cwd=r"C:\path\to\batch\folder")
stdout, stderr = p.communicate()
test.bat
echo Hello World!
pause

Here many guys suggested very useful solutions, but I want to point the importance of where is the program located.
(Bat file is usually made for automation task to reduce time and this has high probability to work some task related path)
import subprocess
os.chdir("YOUR TARGET PATH")
exit_code = subprocess.call(FILEPATH)# FILEPATH is from the standpoint on YOUR TARGET PATH

Related

Running batch file with subprocess.call does not work and freezes IPython console

This is a frequent question, but reading the other threads did not solve the problem for me.
I provide the full paths to make sure I have not made any path formulation errors.
import subprocess
# create batch script
myBat = open(r'.\Test.bat','w+') # create file with writing access
myBat.write('''echo hello
pause''') # write commands to file
myBat.close()
Now I tried running it via three different ways, found them all here on SO. In each case, my IDE Spyder goes into busy mode and the console freezes. No terminal window pops up or anything, nothing happens.
subprocess.call([r'C:\\Users\\felix\\folders\\Batch_Script\\Test.bat'], shell=True)
subprocess.Popen([r'C:\\Users\\felix\\folders\\Batch_Script\Test.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
p = subprocess.Popen("Test.bat", cwd=r"C:\\Users\\felix\\folders\\Batch_Script\\")
stdout, stderr = p.communicate()
Each were run with and without the shell=True setting, also with and without raw strings, single backslashes and so on. Can you spot why this wont work?
Spyder doesn't always handle standard streams correctly so it doesn't surprise me that you see no output when using subprocess.call because it normally runs in the same console. It also makes sense why it does work for you when executed in an external cmd prompt.
Here is what you should use if you want to keep using the spyder terminal, but call up a new window for your bat script
subprocess.call(["start", "test.bat"], shell=True)
start Starts a separate Command Prompt window to run a specified program or command. You need shell=True because it's a cmd built-in not a program itself. You can then just pass it your bat file as normal.
You should use with open()...
with open(r'.\Test.bat','w+') as myBat:
myBat.write('echo hello\npause') # write commands to file
I tested this line outside of ide (by running in cmd) and it will open a new cmd window
subprocess.Popen([r'Test.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
Hey I have solution of your problem :)
don't use subprocess instead use os
Example :
import os
myBatchFile = f"{start /max} + yourFile.bat"
os.system(myBatchFile)
# "start /max" will run your batch file in new window in fullscreen mode
Thank me later if it helped :)

excute .jar file from python

Im trying to access server data via a jar-file. Doing this in MATLAB is quite simple:
javaaddpath('*PATH*\filename.jar')
WWS=gov.usgs.winston.server.WWSClient(ip,port);
Data = eval('WWS.getRawData(var1,var2,var3)');
WWS.close;
Problem is that I need to execute this in Python and I can't figure out how to translate these few lines of code. I've tried using the subprocess module like:
WWS=subprocess.call(['java', 'gov/usgs/winston/server/WWSClient.class'])
but the best I can get is the error "could not find or load main class gov.usgs.winston.server.WWSClient.class"
Thankful for all the help!
Also you can use the following code:
import subprocess
command = "java -jar <*PATH*\filename.jar>"
result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
And result is the output of the jar file.
There are a few ways you can do this. One of the easiest ways is
import subprocess
subprocess.run(["java", "-jar", "*PATH*\filename.jar"])
The python subprocess command runs a system command. It takes a list as an argument, and the list is just the system command you want to run and it's arguments.

run perl script with python

I've been looking at multiple examples on here and elsewhere, but nothing seems for work for me. I know nothing about python. All I am trying to do is run a perl script simply located at
sdb1/media/process.pl
The example code that I've found runs all over the place, and mostly seems like it has extra stuff that I don't need. What I'm trying right now is
#! /usr/bin/python
pipe = subprocess.Popen(["perl", "/sdb1/media/process.pl"], stdout=subprocess.PIPE)
But that just gives me the error
NameError: name 'subprocess' is not defined
If I've missed anything important, let me know. Otherwise, thanks for your time.
you need to import the subprocess library to run subprocess
#! /usr/bin/python
import subprocess
pipe = subprocess.Popen(["perl", "/sdb1/media/process.pl"], stdout=subprocess.PIPE)
Alternatively, if you are just using that same function a lot of times, you can do
from subprocess import Popen
then you can just call
pipe = Popen(["perl", "/sdb1/media/process.pl"], stdout=subprocess.PIPE)
I would have commented but I need 50 rep.

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.
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.
import subprocess
filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
print p.returncode # is 0 if success
Replace \ with / in the path
import os
os.system("D:/xxx1/xxx2XMLnew/otr.bat ")
Probably the simplest way to do this is ->
import os
os.chdir("X:\Enter location of .bat file")
os.startfile("ask.bat")
It is better to write .bat file in such way that its running is not dependent on current working directory, i.e. I recommend to put this line at the beginning of .bat file:
cd "%~dp0"
Enclose filepath of .bat file in double quotes, i.e.:
os.system('"D:\\x\\so here can be spaces\\otr.bat" ["<arg0>" ["<arg1>" ...]]')
To save output of some batch command in another file you can use usual redirection syntax, for example:
os.system('"...bat" > outputfilename.txt')
Or directly in your .bat file:
Application.exe work.xml > outputfilename.txt
You are just missing to make it raw. The issue is with "\". Adding r before the path would do the work :)
import os
os.system(r"D:\xxx1\xxx2XMLnew\otr.bat")
So I do in Windows 10 and Python 3.7.1 (tested):
import subprocess
Quellpfad = r"C:\Users\MeMySelfAndI\Desktop"
Quelldatei = r"\a.bat"
Quelle = Quellpfad + Quelldatei
print(Quelle)
subprocess.call(Quelle)
python_test.py
import subprocess
a = subprocess.check_output("batch_1.bat")
print a
This gives output from batch file to be print on the python IDLE/running console. So in batch file you can echo the result in each step to debug the issue. This is also useful in automation when there is an error happening in the batch call, to understand and locate the error easily.(put "echo off" in batch file beginning to avoid printing everything)
batch_1.bat
echo off
echo "Hello World"
md newdir
echo "made new directory"
If you are trying to call another exe file inside the bat-file.
You must use SET Path inside the bat-file that you are calling.
set Path should point into the directory there the exe-file is located:
set PATH=C:\;C:\DOS {Sets C:\;C:\DOS as the current search path.}

In Python - how to execute system command with no output

Is there a built-in method in Python to execute a system command without displaying the output? I only want to grab the return value.
It is important that it be cross-platform, so just redirecting the output to /dev/null won't work on Windows, and the other way around. I know I can just check os.platform and build the redirection myself, but I'm hoping for a built-in solution.
import os
import subprocess
subprocess.call(["ls", "-l"], stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT)
You can redirect output into temp file and delete it afterward. But there's also a method called popen that redirects output directly to your program so it won't go on screen.

Categories