avatarBetter Everything

Summary

The web content explains how to pass data to a Python script via the command line, demonstrating methods for inputting text and files as arguments to avoid hardcoding data within the script.

Abstract

The article provides a comprehensive guide on passing external data to a Python script during execution. It covers the basic command to run a Python file from the command line and illustrates how to include input data as arguments in the command. The author emphasizes the convenience of using command line arguments to process different inputs without altering the script's content. Techniques for handling text with spaces and passing files containing input data are also discussed, with examples showing how to collect and manipulate these arguments within the Python script using the sys.argv list. The article concludes by encouraging readers to support the author by joining Medium for full access to more content.

Opinions

  • The author suggests that using command line arguments to pass data is preferable to changing hardcoded data in the Python file for each run.
  • Surrounding text with double quotes is recommended when passing text as an argument to prevent it from being split into multiple arguments.
  • The method of passing a filename as an argument and reading its contents within the Python script is presented as an efficient way to handle complex input data.
  • The article implies that the ability to pass data to a Python script enhances its versatility and potential integration with other systems.
  • By inviting readers to join Medium, the author indicates that the platform's membership model supports writers and provides access to a wide range of content.

Passing Data to a Python File when Running It with Commands

Do you have a Python program that uses input data to perfom a certain task? But still unsure how to feed the input data to the script?

This article might help you, because we will discuss passing data to a program when running a Python script.

By using this method you won’t have to change hardcoded data in the Python file each time you want to process different input.

Make your Python script work together with other systems, by allowing input data to be passed to it. Image by catalyststuff on Freepik

Run a Python program from command line

First things first, how do you use a command to a computer to run a Python file?

You can run a Python script by entering a command in the Command Prompt (Windows) or Terminal (Mac): py scriptname.py

Hint: If py doesn’t get recognized, try: python scriptname.py or python3 scriptname.py

Adding input data to run Python command

If we want to add input data we can simply add this separated by spaces to the command. For example:

py scriptname.py 2 Apples 0.25

In the above example, we have passed 3 arguments along with the starting of the script:

  • 2
  • Apples
  • 0.25

Collecting the command line arguments in Python

A list of arguments can easily be collected by importing the standard package sys and using its argv list.

import sys

arguments = sys.argv

Then we can use list indexing to take out the specific arguments. Important note: The first item of the argv list (at index 0) is always the name of the script. This means the first argument can be found at index 1.

amount = arguments[1]
product = arguments[2]
price = arguments[3]

Let’s make a script named arguments.py:

import sys

arguments = sys.argv

print(arguments)

amount = arguments[1]
product = arguments[2]
price = arguments[3]

print(amount,product,price)

We can test it by running this command: py arguments.py 2 Apples 0.25 which will generate this output:

['arguments.py', '2', 'Apples', '0.25']
2 Apples 0.25

Passing text as an argument

We have seen that we can pass text as an argument: Apples. But the arguments are separated by spaces, so if our text would be Red Apples, our text would be split over 2 arguments.

Red Apple or “Red Apple” Image by catalyststuff on Freepik

The solution is to surround the text by double quotes. py arguments.py "Red Apples" After changing the arguments.py script to this:

import sys

arguments = sys.argv

print(arguments[1])

The script outputs: Red Apples

Passing file with input data as an argument

With the above method, using a file as input data becomes really easy.

All we have to do is pass the filename as text and then open the file to read the data. Let’s do it!

As an example we’ll take the file order0001.txt with the following content:

2,Red Apple,0.25 3,Banana,0.20 1,Watermelon,2.00

If we place the file in a folder named Files and place that folder in the same folder as where we have our Python script file_processor.py, we can write our command as: py file_processor.py order0001.txt

This is what we write in Python to open and read the file and get the input data:

import sys

arguments = sys.argv

filename = arguments[1]

with open('Files/'+filename) as f:
    for line in f:
        line = line.strip().split(',')
        amount = line[0]
        product = line[1]
        price = line[2]
        print(amount,product,price)

We open the file by using the open function and within the with clause we will be able to access the file-object f. We can read each line of the text file by looping over the file-object.

By stripping a line, the newline (whitespace) at the end of the line is removed. And by splitting on commas we transform the line into a list with each value as an item.

The ouput will be:

2 Red Apple 0.25
3 Banana 0.20
1 Watermelon 2.00

Thank you for reading!

You can get full access to all my posts by joining Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium:

Python
Programming
Software Development
Automation
Data Engineering
Recommended from ReadMedium