import os import sys # Let wd be the current working directory # # Example usage: # # "python ls" # Prints the contents of wd # "python ls dir" # Prints the contents of wd/dir # "python ls dir subdir subsubdir ..." # Prints the contents of wd/dir/subdir/subsubdir # # # Example output: # # $ python ls # note that the order is undefined # dir # myfile.txt # dir1 def main(): # Get target directory dir_name = parse_args() # Get contents of target contents = os.listdir(dir_name) # Print contents of target print_contents(contents) def parse_args(): ''' Returns the first argument passed to the function at the command line, or the current directory if no such arg was passed. ''' # argv[0] is the name of this script, so we ignore it. args = sys.argv[1:] if len(args) == 0: return os.getcwd() path = "" for token in args: path = os.path.join(path, token) return path def print_contents(contents): ''' Prints the elements of contents, one per line. The order is undefined. ''' for item in contents: print item if __name__ == '__main__': main()