python - 这个Python函数应该如何调用

标签 python function scripting modularity

我在正确引用最近添加的 fpath() 函数时遇到问题。该代码以文件、通配符或文件夹的形式从命令行获取参数,以在最后一个代码块中使用。

#! /usr/bin/env python
import os, sys, glob
from optparse import OptionParser

#logic to determine if argument is a file, folder or wildcard
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():

# List files in directory and upload them
    all_files = ''
    all_files = fpath(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()

最佳答案

以下代码模式存在一些问题:

all_files = ''
def fpath(arguments):
    all_files = []
    # modify all_files
    return all_files 

看起来您想将 all_files 的内容传回调用者。有两种通用方法可以做到这一点,使用全局变量和返回值:

全局变量

要使用全局变量进行此操作,您需要告诉 Python 您将使用 global 语句从函数内修改全局变量:

all_files = ''
def fpath(arguments):
    global all_files
    all_files = []
    # modify all_files

在这种情况下,您也不需要return,因为调用者可以在全局变量中使用结果。

返回值

更好的方法可能是让函数返回all_files:

def fpath(arguments):
    files = []
    # modify files
    return files

all_files = fpath(filename)

这消除了全局变量的使用,这通常被认为是不好的做法,并且容易出现错误和困惑。我还将 fpath 函数内的数组名称更改为 files,以澄清 filesall_files > 确实是不同的变量。它们可以具有相同的名称,但它们仍然是两个不同的变量。

关于python - 这个Python函数应该如何调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5385959/

相关文章:

javascript - 不传递任何参数时不需要括号

python-3.x - 如何使用一个变量中定义的变量并将其用作另一个变量中的参数?

bash - 如何编写一个 Bash 函数来与用户确认现有变量的值

python - 从 ElectronJS 脚本运行 python-shell

python - 从规则 freezeset 中提取字符串

python : Open chrome with parameters

java - 如何使用java通过对象名称打印类的属性?

php - 如何检查是否为 PHP 安装了 memcache 或 memcached?

macos - 如何使用命令行工具为 Mac OS X 创建美观的 DMG?

c++ - 使用 Python 而不是 XML 在 C++ 中加载资源?