使用python从函数外部调用变量

时间:2015-12-17 14:19:24

标签: python

我有这个脚本允许用户通过参数输入文件名,然后更新文件版本:

#!/usr/bin/env python
import os
import sys

class versionBumper:

    def __init__(self):
        self.version = None
        self.SavedBefore = ""
        self.SavedAfter = ""

    def change_version(self, file_to_be_modded, packageVersion):
        for line in file_to_be_modded:
            if packageVersion in line:
                print "VERSION FOUND: ", line
                self.VersionNumber = line
            elif self.VersionNumber is None:
                self.SavedBefore += line
            else:
                self.SavedAfter += line
        file_to_be_modded.close()
        print "Version: ", self.VersionNumber
        return self.VersionNumber

if __name__ == '__main__':
    print "sys.argv[1:]:", sys.argv[0:]
    versionBumper123 = versionBumper()
    filename = sys.argv[1]
    path = "/home/Desktop/Crate/Crate/" + filename + "/build/CMakeLists.txt"

    if os.path.exists:
        inputFile = open(path, 'r')

    else:
        print "no match found"
        sys.exit()

    print "Which version number to bump ?"
    print "1) major"
    print "2) minor."
    print "3) patch."

    Choose_version = raw_input("Choose version: ")

    if Choose_version == "1":
        version = versionBumper123.change_version(inputFile, "_MAJOR ")
    elif Choose_version == "2":
        version = versionBumper123.change_version(inputFile, "_MINOR ")
    elif Choose_version == "3":
        version = versionBumper123.change_version(inputFile, "_PATCH ")
    else:
        print "Invalid input. Exiting gracefully..."
        sys.exit()

    outputFile = open (path, 'w')

    splitted_version_line_substrings = version.split('"')

    Version_Name = splitted_version_line_substrings[0]
    Version_Number = int(splitted_version_line_substrings[1]) + 1
    parenthesis = splitted_version_line_substrings[2]

    new_version = (str(Version_Name) + '"' 
                  + str(Version_Number) + '"' 
                  + str(parenthesis))
    print "new_version: ", new_version

    outputFile.write(str(versionBumper123.SavedBefore))
    outputFile.write(str(new_version))
    outputFile.write(str(versionBumper123.SavedAfter))

但我一直收到这个错误:

Traceback (most recent call last):
  File "untitled.py", line 57, in <module>
    splitted_version_line_substrings = version.split('"')
NameError: name 'version' is not defined. 

我还尝试将version定义为全局变量,但也没有用,我无法弄清楚如何从定义的函数外部调用version

1 个答案:

答案 0 :(得分:0)

我认为您正在处理班级versionBumper

的单个实例
versionBumper123 = versionBumper()

所以我你要用语句做什么

splitted_version_line_substrings = version.split('"')

应表示为

splitted_version_line_substrings = versionBumper123.version.split('"')

仅仅因为您使用了类的单个实例,如果您不使用类,则可以编写更简单的代码。