3kstc
3kstc

Reputation: 1956

Python: Using arguments as variables

I want to use arguments which will then be translated into variable that will hold a value:

I get some values from a CSV file then upload it to Googles' Sheet Docs.

Here is a snippet of my code [mycode.py]:

f101 = open('/home/some_directory/101_Hrs.csv')
f102 = open('/home/some_directory/102_Hrs.csv')
f103 = open('/home/some_directory/103_Hrs.csv')
f112 = open('/home/some_directory/112_Hrs.csv')

csv_f101 = csv.reader(f101)
csv_f102 = csv.reader(f102)
csv_f103 = csv.reader(f103)
csv_f112 = csv.reader(f112)

I want to use an argument (101,102,103 or 112) from the terminal (for example mycode.py 101), where I can use the [101] to be concatenated with the f to getf101 and also open('/home/some_directory/[101]_Hrs.csv') where [101] is a number that can be replaced by the argument from the terminal.

How is this done?

Upvotes: 0

Views: 94

Answers (2)

Brian L
Brian L

Reputation: 3251

A couple of easy tutorials for using input arguments in python programs:

The basic idea is to use the inbuilt sys module, which lets you access the inputs via argv.

import sys

nInputs = len(sys.argv)

print 'Number of arguments = ', nInputs
print 'Inputs = ', str(sys.argv)

if (nInputs >= 2):
    strFilename = '/home/some_directory/' + sys.argv[1] + '_Hrs.csv'
    print 'Filename = ', strFilename

Then when you run:

>> python mycode.py 101
Number of arguments = 2
Inputs = ['mycode.py', '101']
Filename = /home/some_directory/101_Hrs.csv

Upvotes: 1

davejagoda
davejagoda

Reputation: 2528

Check out argparse, which has more features than sys.argv. You don't necessarily need all of them with your current requirements, but it is more flexible and lets you avoid some reinvention:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('arguments', nargs='+')
args = parser.parse_args()
print('number of supplied arguments:{}'.format(len(args.arguments)))
for argument in args.arguments:
    print('supplied argument:{}'.format(argument))

It also has an excellent tutorial written by a frequent Stack Overflow contributor: https://docs.python.org/2/howto/argparse.html

Upvotes: 0

Related Questions