Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Fixing function call in Python script

Posted on 2011-03-22
11
482 Views
Last Modified: 2012-05-11
I am trying to correctly reference the fpath function in the script for use by the last code block. Currently the traceback specifies NameError: global name 'all_files' is not defined.

Any tips would be great.

#! /usr/bin/env python

import os, sys, glob
from optparse import OptionParser

print "ARGS", sys.argv

def fpath(arguments):
    files = []
    for arg in arguments:
        if '*' in arg or '?' in arg:
            # contains a wildcard character
            all_files.extend(glob.glob(arg))
        elif os.path.isdir(arg):
            # is a dictionary
            all_files.extend(glob.glob(os.path.join(arg, '*')))
        elif os.path.exists(arg):
            # is a file
            all_files.append(arg)
        else:
            # invalid?
            print '%s invalid' % arg
    return files

def main():
    usage = "usage: %prog [options] -f filename"
    parser = OptionParser(usage)
    parser.add_option('-d', '--download',
            action='store', dest='download',
            default=None, help='download files from cloud')
    parser.add_option('-f', '--file',
            action='store', dest='filename',
            default=None, help='specify file or wildcard')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()
    (options, args) = parser.parse_args()

# List files in directory and upload them to bucket
    all_files = ''
    all_files = fpath(options.filename)
    for filename in all_files:
        #skip all directory entries which are not a file
        if not os.path.isfile(filename):
              continue
        k.set_contents_from_filename(filename, cb=percent_cb, num_cb=10)

if __name__ == '__main__':
    main()

Open in new window

0
Comment
Question by:adamshields
  • 6
  • 5
11 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35191705
My guess is that you are trying to append to "all_files" in line 19, but it is not in scope.
0
 
LVL 3

Author Comment

by:adamshields
ID: 35191733
So what needs to be done to make this work?
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35191843
You declared the variable files inside of fpath(), but all you do is return it--you don't add anything to it. I think you meant to use files instead of all_files inside of fpath(). Try this:
def fpath(arguments):
    files = []
    for arg in arguments:
        if '*' in arg or '?' in arg:
            # contains a wildcard character
            files.extend(glob.glob(arg))
        elif os.path.isdir(arg):
            # is a dictionary
            files.extend(glob.glob(os.path.join(arg, '*')))
        elif os.path.exists(arg):
            # is a file
            files.append(arg)
        else:
            # invalid?
            print '%s invalid' % arg
    return files

Open in new window

0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 3

Author Comment

by:adamshields
ID: 35191920
With those changes the script runs but the function does not seem to be working correctly. It is parsing the working directory and not any one of the three args.
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 35191964
Well you only passed one item:

all_files = fpath(options.filename)

Open in new window


which appears to be the script's filename. I think what you meant to do was pass the args variable:

all_files = fpath(args)

Open in new window

0
 
LVL 3

Author Comment

by:adamshields
ID: 35192328
Great, that fixed that. One last question on creating functions. Would the following be the best way to make the last block of code a function?

def download(all_files):
    for filename in all_files:
        #skip all directory entries which are not a file
        if not os.path.isfile(filename):
              continue
        k.set_contents_from_filename(filename, cb=percent_cb, num_cb=10)
    #call the function for execution
    download()

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35192502
The definition appears OK, but the way you call it does not. You declared the function to take 1 parameter, but you are calling it with none. Pass the appropriate object in the call and you should be fine.

e.g.
#call the function for execution
#  based on what your code looks like
download(all_files)

Open in new window

0
 
LVL 3

Author Comment

by:adamshields
ID: 35192617
The download() function contains a reference to the fname() funciton, is there a way to handle args without defining globally?

def download(all_files):
    all_files = fname(args)
    for filename in all_files:
        #skip all directory entries which are not a file
        if not os.path.isfile(filename):
              continue
        k.set_contents_from_filename(filename, cb=percent_cb, num_cb=10)

Open in new window


Traceback:

Traceback (most recent call last):
  File "./backup.py", line 109, in <module>
    main()
  File "./backup.py", line 95, in main
    download(all_files)
  File "./backup.py", line 33, in download
    all_files = fname(args)
NameError: global name 'args' is not defined
0
 
LVL 75

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 500 total points
ID: 35192721
Pass it as a parameter:

def download(all_files, args):
    all_files = fname(args)
    for filename in all_files:
        #skip all directory entries which are not a file
        if not os.path.isfile(filename):
              continue
        k.set_contents_from_filename(filename, cb=percent_cb, num_cb=10)

Open in new window


Calling:
download(all_files, args)

Open in new window

0
 
LVL 3

Author Closing Comment

by:adamshields
ID: 35193422
Thanks!
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35193521
NP. Glad to help  = )
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

860 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question