给函数提供参数并以正确的方式加载函数

时间:2016-04-11 18:09:45

标签: python function arguments

我是python的新手,也是编程的新手。也许你可以帮我解决以下问题:

我有2个文件:warmaker.py和functions.py

我有2个问题。

  1. 当我使用参数-i作为inputfile时,如何将此变量的值(例如test.zip)切换到我的函数unzip()?
  2. 如何以正确的方式调用此功能?
  3. warmaker.py

    "item1": 
      {"accountSet":"1", "item1field1": "asdf", "item1field2": "ghyj"},
    "item2": {"item2field2": "111"} 
    

    functions.py

    def main(argv):
        try:
            opts, args = getopt.getopt(argv, "hi:o:d", ["help", "ifile=", "ofile="])
        except getopt.GetoptError:
            functions.usage()
            sys.exit(2)
    
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                functions.usage()
                sys.exit()
            elif opt in '-d':
                global _debug
            elif opt in ("-i", "--ifile"):
                global ifile
                ifile = arg
            elif opt in ("-o", "--ofile"):
                global ofile
                ofile = arg
    
        functions.unzip(ifile)
    
    if __name__ == "__main__":
        main(sys.argv[2:])
    

    也许你可以帮助我?

    亲切的问候

3 个答案:

答案 0 :(得分:0)

这是控制台上的输出:

root@osboxes:~/PycharmProjects/warmaker# python warmaker.py -i CS_A3.war 
Before
after.zip
Changing extension from .zipto .zip

Start to unzip .zip
 ...
Traceback (most recent call last):
  File "warmaker.py", line 33, in <module>
    main(sys.argv[2:])
  File "warmaker.py", line 30, in main
    functions.unzip(ifile)
  File "/root/PycharmProjects/warmaker/functions.py", line 17, in unzip
    extract = zipfile.ZipFile(ifile)
  File "/usr/lib/python2.7/zipfile.py", line 756, in __init__
    self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: '.zip'

正如你所看到的,在“之前”之后,必须有varibale“ifile”的值但是没有

答案 1 :(得分:0)

在warmaker.py中,你有

if __name__ == "__main__":
    main(sys.argv[2:])

将其更改为

if __name__ == "__main__":
    main(sys.argv[1:])

选项从sys.argv [1]开始。

sys.argv [0]是Python文件的名称。

答案 2 :(得分:0)

我编辑它以使用argparse(这是主要的API参考;它还有一个链接到更接近顶部的初学者友好教程)而不是optparse,因为文档说optparse已被弃用

你有东西设置为使用主要功能&amp;一个if __name__ =='__ main__'成语,这很好,但这里并不需要它,所以我在编辑中简化了一些东西。如果你将warmaker.py代码放在w / functions.py代码中的单个文件(又称模块)中,那么你想使用if __name__ =='__ main__'以便你可以导出函数w / out你在warmaker.py的主要功能中运行的代码,但是像这样它很好w / out

warmaker.py

import argparse
import functions

parser = argparse.ArgumentParser()
parser.add_argument('-i', '--ifile')
parser.add_argument('-o', '--outdir', help='specify the output dir. default is . (ie, the cwd)')
args = parser.parse_args()


if args.outdir:
    functions.unzip(args.ifile, outdir=args.outdir)
else:
    functions.unzip(args.ifile)

functions.py

import os
import zipfile
import sys

def usage():
    print "\nHow to use warmaker.py"
    print 'Usage: '
    print 'python ' + sys.argv[0] + ' -i <inputfile> -o <output directory (optional)>'
    # note that in python, if you concatenate a string then print it, you have to add the space chars yourself


def unzip(ifile, outdir='.'):
    print 'Unzipping', ifile
    prev_content = set(os.listdir(outdir))
    print " ... "
    with zipfile.ZipFile(ifile) as efile:
        efile.extractall(outdir)
    added_content = set(os.listdir(outdir)) - prev_content
    print ifile, 'successfully extracted'
    # calling print on variables separated by commas prints them separated by a space by default
    print 'extracted contents:'
    for n, name in enumerate(added_content):
        print n+1, name

此外,我将其更改为您可以指定输出目录而不是文件&amp;我添加了一些代码来显示添加了哪些新文件/目录,以及我认为你想要的内容。给出一个输出文件似乎并不完全匹配ZipFile上的文档说你可以做什么w / extractall方法。如果这是一个仅对压缩的单个文件进行操作的自定义用法&amp;需要以这种方式工作,你需要改变functions.py基本

总的来说,对于编程新手来说,这是非常可靠的代码。干得好