0Interest
0Interest

Reputation: 1842

Make a batch file run a python code with arguments

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!

Upvotes: 0

Views: 11063

Answers (3)

Yash Kumar Atri
Yash Kumar Atri

Reputation: 795

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]

Upvotes: 4

0Interest
0Interest

Reputation: 1842

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

Upvotes: 0

Kenny Song
Kenny Song

Reputation: 1

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.

Upvotes: 0

Related Questions