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)
6
  • . === current working directory. Commented Jan 10, 2014 at 7:45
  • 1
    "." used to refer current directory (it is Linux concept) and ".." for parent directory. Try cd . and cd .. on your system. Commented Jan 10, 2014 at 7:45
  • @GrijeshChauhan I thought that one could use . and .. on Win & Mac too. Commented Jan 10, 2014 at 7:46
  • @devnull yes I know it is valid in Mac, but I will give it a try in Win. Thanks!.. Commented Jan 10, 2014 at 7:51
  • 1
    @GrijeshChauhan Never mind, who uses the command line on Windows anyways? Commented Jan 10, 2014 at 7:52

3 Answers 3

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 "."

Sign up to request clarification or add additional context in comments.

Comments

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
>>> 

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.