Thursday, October 29, 2026
HomeArtificial IntelligenceCommand line arguments to your Python script

Command line arguments to your Python script

[ad_1]

Final Up to date on February 26, 2022

Engaged on a machine studying venture means we have to experiment. Having a approach to configure your script simply will provide help to transfer sooner. In Python, we have now a approach to adapt the code from command line. On this tutorial, we’re going to see how we are able to leverage the command line arguments to a Python script that will help you work higher in your machine studying venture.

After ending this tutorial, you’ll be taught

  • Why we wish to management a Python script in command line
  • How we are able to work in a command line effectively

Let’s get began.

Command line arguments to your Python script

Command line arguments to your Python script. Picture by insung yoon. Some rights reserved

Overview

This tutorial is in three components, they’re

  • Operating a Python script in command line
  • Engaged on the command line
  • Various to command line arguments

Operating a Python script in command line

There are numerous methods to run a Python script. Somebody could run it as a part of a Jupyter pocket book. Somebody could run it in an IDE. However in all platforms, it’s at all times doable to run a Python script in command line. In Home windows, you may have the command immediate or PowerShell (and even higher, the Home windows Terminal). In macOS or Linux, you may have the Terminal or xterm. Operating a Python script in command line is highly effective as a result of you possibly can cross in extra parameter to the script.

The next script permits us to cross in values from the command line into Python:

Once we save these few traces right into a file, and run it in command line with an argument:

you will note it takes our argument, convert it into integer, add one into it and print. The checklist sys.argv comprises the identify of our script and all of the arguments (all strings), which within the above case, it’s ["commandline.py", "15"].

Once you run a command line with extra difficult set of arguments, it takes some effort to course of the checklist sys.argv. Subsequently Python offered the library argparse to assist. That is to imagine GNU-style, which will be defined utilizing the next instance:

The optionally available arguments are launched by “-” or “--“, which a single hyphen is to hold a single character “quick possibility” (resembling -a, -B and -v above), and two hyphens are for a number of characters “lengthy choices” (resembling --exclude and --ignore-existing above). The optionally available arguments could have extra parameters, resembling in -B 1024 or --exclude="*.pyc", the 1024 and "*.pyc" are parameters to -B and --exclude respectively. Moreover, we can also have obligatory arguments, which we simply put them into the command line. The half 192.168.0.3:/tmp/ and ./ above are examples. The order of obligatory arguments are necessary. For instance, the rsync command above will copy recordsdata from 192.168.0.3:/tmp/ to ./ as an alternative of the opposite manner spherical.

The next is to duplicate the above instance in Python utilizing argparse:

For those who run the above script, you will note:

That is to imply you didn’t present the obligatory arguments for src and dest. Maybe the most effective cause to make use of argparse is to get a assist display screen totally free should you provded -h or --help because the argument, like the next:

Whereas the script did nothing actual, should you offered the arguments as required, you will note this:

The parser object created by ArgumentParser() has a parse_args() technique that reads sys.argv and returns a namespace object. That is an object that carries attributes and we are able to learn utilizing args.ignore_existing for instance. However often it’s simpler to deal with if it’s a Python dictionary. Therefore we are able to convert it into one utilizing vars(args).

Normally for all optionally available arguments, we offer the lengthy possibility and generally additionally the quick possibility. Then we are able to entry the worth offered from the command line utilizing the lengthy possibility as the important thing (with hyphen changed with underscore, or the single-character quick possibility as the important thing if we don’t have an extended model). The “positional arguments” will not be optionally available and their names are offered within the add_argument() perform.

There are a number of sorts of arguments. For the optionally available arguments, generally we use them as a boolean flags however generally we count on them to herald some knowledge. Within the above, we use motion="store_true" to make that possibility set to False by default and toggle to True whether it is specified. For the opposite possibility resembling -B above, by default it expects extra knowledge to go following it.

We are able to additional require an argument to be a particular kind. For instance the -B possibility above, we are able to make it to count on integer knowledge by including kind like the next

and if we offered the mistaken kind, argparse will assist terminate our program with an informative error message:

Engaged on the command line

Empowering your Python script with command line arguments can convey it to a brand new stage of reusability. First, let’s take a look at a easy instance on becoming an ARIMA mannequin to GDP time collection. World Financial institution collected historic GDP knowledge of many international locations. We are able to make use of the pandas_datareader bundle to learn the info. For those who haven’t put in it but, you need to use pip (or conda should you put in Anacronda) to put in the bundle:

The code for the GDP knowledge that we use is NY.GDP.MKTP.CN, we are able to get the info of a rustic within the type of a pandas DataFrame by

after which we are able to tidy up the DataFrame a bit utilizing the instruments offered by pandas:

then becoming an ARIMA mannequin and use the mannequin for prediction is just not troublesome. Within the following, we match utilizing the primary 40 knowledge factors and forecast for subsequent 3. Then evaluate the forecast with the precise by way of relative error:

Placing all of it collectively, and just a little sprucing, the next is the entire code:

This script prints the next output

The above code is brief however we made it versatile sufficient by holding some parameters in variables. We are able to change the above code to make use of argparse so we are able to change some parameters from the command line, as follows:

If we run the code above in a command line, we are able to see it could now settle for arguments:

Within the final command above, we cross in -c NO to use the identical mannequin to the GDP knowledge of Norway (NO) as an alternative of Sweden (SE). Therefore, with out the chance of messing up the code, we reused our code to a distinct dataset.

The ability of introducing command line argument is that we are able to check out our code with various parameters simply. For instance, we wish to see if ARIMA(1,1,1) mannequin is an efficient mannequin for predicting GDP and we wish to confirm with completely different time window of the nordic international locations:

  • Denmark (DK)
  • Finland (FI)
  • Iceland (IS)
  • Norway (NO)
  • Sweden (SE)

We wish to verify for the window of 40 years however with completely different beginning factors (since 1960, 1965, 1970, 1975). Will depend on the OS, you possibly can construct a for loop in Linux and mac utilizing the bash shell syntax:

or, because the shell syntax permits, we are able to put the whole lot in a single line:

and even higher, give some info at every iteration of the loop, and we get our script run a number of occasions:

For those who’re utilizing Home windows, you need to use the next syntax in command immediate:

or the next in PowerShell:

each ought to produce the identical consequence.

Whereas we are able to put comparable loop inside our Python script, generally it’s simpler if we are able to do it on the command line. It could possibly be extra handy once we are exploring completely different choices. Furthermore, by taking the loop exterior of the Python code, we will be assured that each time we run the script is impartial as a result of we is not going to share any variables between iterations.

Utilizing command line arguments is just not the one approach to cross in knowledge to your Python script. Not less than, there are a number of different methods too:

  • utilizing setting variables
  • utilizing config recordsdata

Surroundings variables are options out of your OS to maintain small quantity of knowledge in reminiscence. We are able to learn setting variables in Python utilizing the next syntax:

For instance, in Linux, the above two-line script will work with the shell as follows

and in Home windows, the syntax inside command immediate is analogous:

You might also add or edit setting variables in Home windows utilizing the dialog in Management Panel:

So we could maintain the parameters to the script in some setting variables and let the script adapt its conduct like establishing command line arguments.

In case we have now numerous choices to set, it’s higher to avoid wasting the choices to a file quite than overwhelming the command line. Will depend on the format we selected, we are able to use the configparser or json module from Python for studying Home windows INI format or JSON format respectively. We can also use the third occasion library PyYAML to learn YAML format.

For the above instance on operating ARIMA mannequin on GDP knowledge, we are able to modify the code to make use of YAML config file:

and the YAML config file is known as as config.yaml, which its content material is as follows:

Then we are able to run the above code and acquiring the identical consequence as earlier than. The JSON counterpart may be very comparable, which we use the load() perform from json module:

and the JSON config file, config.json can be

It’s possible you’ll be taught extra in regards to the syntax of JSON and YAML to your venture. However the thought right here is that we are able to separate the info and algorithm for higher reusability of our code.

Additional studying

This part offers extra sources on the subject if you’re trying to go deeper.

Libraries

Articles

Books

Abstract

On this tutorial, you’ve see how we are able to make use of the command line for extra environment friendly management of our Python script. Particularly, you discovered

  • How we are able to cross in parameters to your Python script utilizing the argparse module
  • How we are able to effectively management the argparse-enabled Python script in a terminal underneath completely different OS
  • We are able to additionally use setting variables, or config recordsdata to cross in parameters to a Python script



[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments