0

how do I make a python code that runs a .bat (batch) file, and the .bat file
calls another python with arguments?
I know that if you want to call a python file using .bat you need to write:

C:\python27\python.exe D:\XXX\XXX\XXX\XXX.py %*

what about arguments? I need this D:\XXX\XXX\XXX\XXX.py file to get args... Thanks!

1
  • Is your problem passing arguments from the batch script, or receiving arguments in the Python script? Commented Sep 30, 2018 at 15:45

3 Answers 3

4

If you want to run a batch file from python program you should do the following

OS : Windows

run.py

import os
os.system("<bat_file_name> argument1 argument2 argument3")

In batch file

run.bat

echo %1
echo %2
echo %3

These will print all your 3 arguments.

In case you wanna excute a python script using batch

run.py

python run.py argument1 argument2 argument3

and In python file you will grab them as

import sys
arg1 = sys.argv[1]
arg1 = sys.argv[2]
arg1 = sys.argv[3]
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, I need to use check_input using subprocess. is it the same?
Not working... 'bash' is not recognized as an internal or external command, operable program or batch file.
you are on windows then run it without bash
I think you meant %1 , %2 .. instead of $1 $2 .. no? because with % it works fine
0
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("foo")
parser.add_argument("bar")
args = parser.parse_args()

print(args.foo, args.bar)

Above code is a python code for simple argparse example. Name this as example.py

Your bat file should be like

C:\python27\python.exe D:\XXX\XXX\XXX\example.py hello world

A simple single line code.

Save this batch file as example.bat somewhere and execute this at the cmd window.

2 Comments

what is the "hello world" after the .py for?
those are the two arguments
0

Thanks for the answers!

if you want to get arguments from python to batch,
you simply pass them one by one with space in between, for example:

output = subprocess.check_output("abc.bat "+ arg1 + " " + arg2)

and to use them in the batch file:

%1 - for the first argument
%2 - for the second argument
%3 - for the third argument

and so forth.

Thanks :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.