How Do You Write a Python Program to Accept Input in a Non-interactive Way at Run-time?

Problem scenario
You are used to using "input" with Python 3 to prompt the user for a value. How do you pass input when you execute a Python program?

Solution
1. Use import sys

2. Use sys.argv[1] to refer to the first argument passed when you run your program like this:

python3 goodprog.py foo

The program will see "sys.argv[1]" as the string "foo".

Here is another example: python3 goodprog.py bar

The program will see "sys.argv[1]" as the string foo. The program will see "sys.argv[2]" as the string bar.

Leave a comment

Your email address will not be published. Required fields are marked *