使用另一个Python文件中的变量

时间:2017-07-18 16:03:27

标签: python python-2.7 class variables

我有两个不同的.py文件,是否可以在另一个中使用一个变量?

对不起我的错误代码,但我还在学习:)

在MainFile.py中

-i

在LoginFile.py中我有:

from LoginFile import login

class MyApp(QtGui.QDialog, Ui_login_dialog):
    def __init__(self, parent=None):
        super(MyApp,self).__init__()
        self.setupUi(self)
        self.login_btn.clicked.connect(self.loginCheck)
        self.Register.clicked.connect(self.registerCheck)
        self.window2 = None
        total_usernames = c.execute("SELECT USERNAME FROM register_table").fetchall()
        for data in total_usernames:
            self.comboBox.addItems(data)

    def login_check(self):
        username = str(self.comboBox.currentText())
        password = str(self.fieldpassword.text())

        login(username, password)

        # I can't read the following variables from the other file
        print(current_status)    
        print(current_username)

基本上我想读一下从LoginFile.py导入的MainFile.py中的“current_status”和“current_username”变量

我已经尝试从其他文件导入所有内容:

 def login(username, password):
     driver=webdriver.Chrome(r"C:\Python27\selenium\webdriver\chromedriver.exe")
     driver.get(site)
     current_username = driver.find_element_by_xpath(".//*[@id='react-root']/section/main/article/header/div[2]/ul/li[1]/span/span").text
     current_status = driver.find_element_by_xpath(".//*[@id='react-root']/section/main/article/header/div[2]/ul/li[2]/a/span").text

但它不起作用。我也尝试检查类似问题的答案,但我无法找到适用于我的解决方案。

有可能吗?是否有更好的解决方案来达到相同的结果?

非常感谢提前!!!

3 个答案:

答案 0 :(得分:1)

您尝试导入的变量位于函数内部,因此它们超出了范围。即使你调用了函数,它们也会在函数结束时被销毁,除非你返回它们。另一种方法是将它们和其他逻辑放在函数之外然后导入逻辑将被执行并分配变量,那么你就可以访问了他们的价值观。所有这一切都假设您在解释器点击导入的行时没有收到任何错误。

答案 1 :(得分:0)

from LoginFile import *使您可以访问LoginFile类/模块中编写的所有函数,而不是其变量。访问该类中的变量的常见解决方法是简单地使用另一个函数,如getVariable(),它只返回感兴趣的变量。然后在MainFile中通过LoginFile.getVariable()调用该函数。

答案 2 :(得分:0)

将目录定义为python目录/包,目录结构如

/directory 
    __init__.py
    main.py
    LoginFile.py