2

Quick question on passing arugments from sys. In the code below, I don't understand the data_dir = "." This data_dir is used in another section to represent a file directory, but I don't understand the = "." piece. I had thought sys.argv would only pass one arugment, the file name that could be usedin in the function main. Any help would be appreciated!

def main(name, data_dir ="."):
    resp = Respondents()
    resp.ReadRecords(data_dir)
    print 'Number of respondents', len(resp.records)

    preg = Pregnancies()
    preg.ReadRecords(data_dir)
    print 'Number of pregnancies', len(preg.records)

if __name__ == '__main__':
    main(*sys.argv)

3 Answers3

1

The * before sys.argv causes the list to expand out into all the arguments of the function. So sys.argv[0] is passed to name, and if it exists, sys.argv[1] is passed to data_dir, overriding "."

mhlester
  • 22,781
  • 10
  • 52
  • 75
0

Hope this example helps in understanding how *sys.argv works. data_dir="." parameter of the main() function is actually a default parameter i.e if you don't pass a value for data_dir, python takes its value to be "." which stands for the current directory in UNIX.

>>> 
>>> def main(name, data_dir = "."):
...     print name
...     print data_dir
... 
>>> import sys
>>> sys.argv
['']
>>> sys.argv[0] = "some_file_name"
>>> 
>>> main(*sys.argv)
some_file_name
.
>>> 
>>> sys.argv.append("my_data_dir")
>>> main(*sys.argv)
some_file_name
my_data_dir
>>> 
praveen
  • 3,193
  • 2
  • 26
  • 30
0

"." is the defaut value for data_dir, it means the current directory which program runs.