How to pass arguments to batch file in python

I searched the site, but I didn't see anything quite matching what I was looking for. I created a stand-alone application that uses a web service I created. To run the client I use:

C:/scriptsdirecotry> "run-client.bat" param1 param2 param3 param4

How would I go about coding this in Python or F#. It seems like it should be pretty simple, but I haven't seen anything online that quite matches what I'm looking for.

Ross Ridge

37.4k7 gold badges77 silver badges110 bronze badges

asked May 26, 2010 at 20:58

1

Python is similar.

import os
os.system["run-client.bat param1 param2"]

If you need asynchronous behavior or redirected standard streams.

from subprocess import *
p = Popen[['run-client.bat', param1, param2], stdout=PIPE, stderr=PIPE]
output, errors = p.communicate[]
p.wait[] # wait for process to terminate

answered May 27, 2010 at 0:33

gradbotgradbot

13.6k5 gold badges36 silver badges69 bronze badges

6

In F#, you could use the Process class from the System.Diagnostics namespace. The simplest way to run the command should be this:

open System.Diagnostics
Process.Start["run-client.bat", "param1 param2"]

However, if you need to provide more parameters, you may need to create ProcessStartInfo object first [it allows you to specify more options].

answered May 26, 2010 at 21:04

Tomas PetricekTomas Petricek

236k19 gold badges367 silver badges539 bronze badges

Or you can use fsi.exe to call a F# script [.fsx]. Given the following code in file "Script.fsx"

#light

printfn "You used following arguments: "
for arg in fsi.CommandLineArgs do
  printfn "\t%s" arg

printfn "Done!"

You can call it from the command line using the syntax:

fsi --exec .\Script.fsx hello world

The FSharp interactive will then return

You used following arguments:
        .\Script.fsx
        hello
        world
Done!

There is more information about fsi.exe command line options at msdn: //msdn.microsoft.com/en-us/library/dd233172.aspx

answered May 28, 2010 at 10:20

HuusomHuusom

5,4441 gold badge16 silver badges15 bronze badges

Running Python scripts from the command line can be a great way to automate your workflows. To do this, you’ll need to learn how to pass arguments from the command line to a Python script. This will allow you to create reusable scripts that can be updated, or run for new situations or data by just passing in a couple of new arguments. In Python getting arguments from the command line to a script is quite easy.

Before you can pass arguments to a script, you’ll need to understand how to run a Python script from the command line. Follow this tutorial for a step-by-step guide.

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys [sys.argv] will store all the information in the command line entry and can be accessed inside the Python script. Python’s getopt module can also be used to parse named arguments.

Let’s go through some examples.

To start, we’ll create a script that prints out the entire command line statement. Then we can examine how the arguments are passed and learn how to incorporate those into our code.

In the Python script, we’ll import sys, then just print out the full value of sys.argv. The script looks like this.

import sys

print['cmd entry:', sys.argv]

Save this script as myscript.py. Now we’ll call this script from the command line [follow this tutorial if you need directions], as follows. Make sure your working directory is the same directory that contains myscript.py.

You’ll notice when I call the script that I’ve included three arguments separated by a space [arg1, arg2, and arg3]. These are just to illustrate how sys stores and displays the arguments. They don’t have any meaning.

Here’s my call to myscript.py from the command line. The second line of code shows the output.

>>> c:\code\python\tutorials\cmd_scripts>python myscript.py arg1 arg2 arg3
cmd entry: ['myscript.py', 'arg1', 'arg2', 'arg3']

You can see that sys.argv has stored the arguments as strings in a list. Let’s try this again with different data types [float, int, and string] to see how they are stored.

Here’s the script call and output.

>>> c:\code\python\tutorials\cmd_scripts>python myscript.py 198.3 9 arg3
cmd entry: ['myscript.py', '198.3', '9', 'arg3']

As you can see, the float and integer were also stored as strings by sys.argv.

Accessing Command Line Arguments in a Python Script

Now that we have some basic information about how to access command-line arguments and how they are stored, we can start parsing those arguments for use in our script.

In this simple example, we’ll iterate through each argument [except the first one, which is the script name] and print it to the console.

Let’s start by updating the Python script, myscript.py. We’ll add a loop to iterate through the last three arguments in sys.argv. For each element, we’ll print out its index [or position] and its value.

Here’s the new script. Notice that we iterate through a range that starts at 1. This skips the first argument, which is the script name.

import sys

for i in range[1, len[sys.argv]]:
    print['argument:', i, 'value:', sys.argv[i]]

Run the script using the last set of arguments. Like this.

>>> c:\code\python\tutorials\cmd_scripts>python myscript.py 198.3 9 arg3

You should get output that looks like this.

argument: 1 value: 198.3
argument: 2 value: 9
argument: 3 value: arg3

That gives you the basics of passing command-line arguments to a Python script. From here, you’ll probably want to do some logical checks to make sure the input values are the appropriate types and fall within the correct range or set of values.

Improved Parsing of Python Command Line Arguments

The examples above provide simple examples to get you started. However, if you’re looking for something more advanced that allows users to specify arguments with keywords and print help messages we’ll need to get a little more advanced.

To retrieve named arguments from the command line we’ll use Python’s getopt module. getopt is built into base Python so you don’t need to install it.

Let’s start a new script that uses both sys and getopt to parse command-line arguments. The script will have the possibility of four named arguments, ‘help’, ‘input’, ‘user’, and ‘output’. From the command line, these arguments can be specified with a single dash and the first letter [-h] or a double dash and the full argument name [--help]. Name this script myscript2.py.

This script will consist of two parts. The first part is a function [myfunc] that will take the arguments [argv] as an input. The second part is an if statement that will recognize when the script is called and pass the arguments from sys.argv to myfunc.

In the body of myfunc, we’ll define variables for the input, user, and output. We’ll also define a variable for ‘help’ and give it a value. The ‘help’ variable will print out if an error is thrown or if the user specifies -h or --help.

Now call getopt.getopt and pass it the arguments from the command line, but not the script name [like this: argv[1:]]. In the call to getopt is also where we specify both the parameter short and long names. The colons [:] following i, u, and o indicate that a value is required for that parameter. The equal signs [=] following input, user, and output indicate the same.

I’ve put the call to getopt.getopt into a try except statement so that the script will print the help message and then exit if there are any problems. Here’s what the script looks like so far.

import sys
import getopt


def myfunc[argv]:
    arg_input = ""
    arg_output = ""
    arg_user = ""
    arg_help = "{0} -i  -u  -o ".format[argv[0]]
    
    try:
        opts, args = getopt.getopt[argv[1:], "hi:u:o:", ["help", "input=", 
        "user=", "output="]]
    except:
        print[arg_help]
        sys.exit[2]


if __name__ == "__main__":
    myfunc[sys.argv]

In the final part of the script, we’ll parse the arguments based on their short or long names, or keywords, and print out the final values.

To start, loop through all the elements of opts. This will return the argument name [opt] and value [arg]. Then use an if, elif, else statement to determine which variable to assign the argument to. After all the arguments have been handled, print out the argument name and its value.

The final script should look similar to this.

import sys
import getopt


def myfunc[argv]:
    arg_input = ""
    arg_output = ""
    arg_user = ""
    arg_help = "{0} -i  -u  -o ".format[argv[0]]
    
    try:
        opts, args = getopt.getopt[argv[1:], "hi:u:o:", ["help", "input=", 
        "user=", "output="]]
    except:
        print[arg_help]
        sys.exit[2]
    
    for opt, arg in opts:
        if opt in ["-h", "--help"]:
            print[arg_help]  # print the help message
            sys.exit[2]
        elif opt in ["-i", "--input"]:
            arg_input = arg
        elif opt in ["-u", "--user"]:
            arg_user = arg
        elif opt in ["-o", "--output"]:
            arg_output = arg

    print['input:', arg_input]
    print['user:', arg_user]
    print['output:', arg_output]


if __name__ == "__main__":
    myfunc[sys.argv]

Let’s use this script in a couple of different ways to see what happens.

First, let’s get the help message using both the short -h and long --help names.

>>> c:\code\python\tutorials\cmd_scripts>python myscript2.py -h
myscript2.py -i  -u  -o 
>>> c:\code\python\tutorials\cmd_scripts>python myscript2.py --help
myscript2.py -i  -u  -o 

As expected, both examples resulted in the help message printing to the console.

Next, let’s see what happens if we specify an invalid argument name, --madeup.

>>> c:\code\python\tutorials\cmd_scripts>python myscript2.py --madeup
myscript2.py -i  -u  -o 

This caused an error, which resulted in the help message printing to the console again.

Now, let’s enter the correct arguments.

>>> c:\code\python\tutorials\cmd_scripts>python myscript2.py -i inputfile -u myusername -o outputfile
input: inputfile
user: myusername
output: outputfile

The arguments were assigned to the appropriate variables.

Next Steps

This article gives you a primer on passing and parsing command line arguments with Python. For a full-fledged implementation, there is still more work you will want to do. It will be important to check the types and values of the input arguments to be sure they are valid. You’ll also want to make sure to print out helpful messages to the user when an error or other exception occurs. If you’re just implementing this for personal use, those features aren’t so important. I’ve found that writing my Python scripts to run from the command line has helped me automate many of my tasks and analyses and has saved me lots of time.

Learn GIS From Industry Professionals

Whether you’re looking to take your GIS skills to the next level, or just getting started with GIS, we have a course for you! We’re constantly creating and curating more courses to help you improve your geospatial skills.

All of our courses are taught by industry professionals and include step-by-step video instruction so you don’t get lost in YouTube videos and blog posts, downloadable data so you can reproduce everything the instructor does, and code you can copy so you can avoid repetitive typing

Can you pass arguments to a batch file?

In the batch script, you can get the value of any argument using a % followed by its numerical position on the command line. The first item passed is always %1 the second item is always %2 and so on. If you require all arguments, then you can simply use %* in a batch script.

How do you pass arguments to a Python script?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys [ sys. argv ] will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.

How many arguments can be passed to a batch file?

There is no practical limit to the number of parameters you can pass to a batch file, but you can only address parameter 0 [%0 - The batch file name] through parameter 9 [%9].

What does %% do in batch file?

Use double percent signs [ %% ] to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

Chủ Đề