Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: pass arguments to a script [duplicate]

I have a working code to print random lines from a csv column.

#!/usr/bin/python

import csv
from random import shuffle

filename = 'example.csv'
col = 2
sample = 100

with open(filename, 'r') as f:
    reader = csv.reader(f)
    data = [row[col] for row in reader]
    shuffle(data)
    print '\n'.join(data[:sample])

How can I parameterize this script by passing filename, col & sample (e.g. 100 values)?

like image 999
sumoka Avatar asked Apr 13 '26 20:04

sumoka


1 Answers

You can use the sys module like this to pass command line arguments to your Python script.

import sys

name_of_script = sys.argv[0]
position = sys.argv[1]
sample = sys.argv[2]

and then your command line would be:

./myscript.py 10 100
like image 80
Genome Avatar answered Apr 15 '26 08:04

Genome