Jurgen Farrugia
Jurgen Farrugia

Reputation: 21

Passing a value to a python variable from batch script

I have the below python script which takes a user input that is eventually used by the program to read a particular file.

I want to execute the python program from batch script and pass the file_name in the batch script. Can someone please help?

file_name = input("Input File Name to Compare: ")

path = ("outward\\" + file_name)

Upvotes: 2

Views: 2284

Answers (3)

Erling Olsen
Erling Olsen

Reputation: 740

To run the Python program from the batch script and pass the filename into the batch script, you need to use sys, so:

import sys

sys.argv is automatically a list of strings representing arguments on the command line. You can use this as an input for your program. Represents the first command line argument (like a string) given to the script in question.

The lists are indexed by numbers based on zero, so you can get the individual items using the syntax [0]. To get the script name, you need to get the first argument after the script for a filename, so:

filename = sys.argv[1]
path = "outward\\" + file_name

Next you need to pass it to your script like this:

$ python your_script.py filename.ext

(not to be confused with .ext with .text)

Your complete code for the solution to the question, quite simply, will be:

import sys

filename = sys.argv[1]
path = "outward\\" + file_name

and

   $ python your_script.py filename.ext

Upvotes: 1

Abstrogic
Abstrogic

Reputation: 37

You could use the sys.argv Python function.

The idea would be to get the input from the user in the batch file, then execute the Python program from the batch file while passing the user input as a command line argument to the python file. Example:

batchfile.bat

@echo off
set /p file="Enter Filename: "

python /path/to/program/pythonprogram.py %file%

pythonprogram.py

import sys 
 
sys.argv[0] = file_name
path = ("outward\\" + file_name)

Now, when you execute the batch file, it will prompt for user input of a filename. Then, it will execute the Python program while passing the filename as a command-line argument to the Python file. Then using the sys.argv function you can collect the argument.

Upvotes: 0

eshirvana
eshirvana

Reputation: 24593

import sys
file_name = sys.argv[1]
path = "outward\\" + file_name

and you pass it to your script like:

$ python script.py filename.ext

Upvotes: 1

Related Questions