akosipolan
Posts: 13
Joined: Sat Jul 19, 2014 7:16 am

access variable from another python file

Sat Jul 25, 2015 2:48 am

hi guys, just want to ask how would i access the variable from another python file. here's my code.
mymain.py

Code: Select all

from PyQt4 import QtCore, QtGui
import PyQt4
import sys
import os
from time import sleep

global myctr
global myval
myip = 0


try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        self.showMaximized()
        MainWindow.setStyleSheet(_fromUtf8("background-color: rgb(0, 0, 0);"))
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 2, 0, 1, 1)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.lblNowServing = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Bebas Neue"))
        font.setPointSize(140)
        self.lblNowServing.setFont(font)
        self.lblNowServing.setStyleSheet(_fromUtf8("color: rgb(170, 0, 0);"))
        self.lblNowServing.setObjectName(_fromUtf8("lblNowServing"))
        self.lblNowServing.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout.addWidget(self.lblNowServing)
        global lblNowServingNumber
        lblNowServingNumber = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("DS-Digital"))
        font.setPointSize(350)
        lblNowServingNumber.setFont(font)
        lblNowServingNumber.setStyleSheet(_fromUtf8("color: rgb(170, 0, 0);"))
        lblNowServingNumber.setObjectName(_fromUtf8("lblNowServingNumber"))
        lblNowServingNumber.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout.addWidget(lblNowServingNumber)
        self.horizontalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.lblCounter = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Bebas Neue"))
        font.setPointSize(140)
        self.lblCounter.setFont(font)
        self.lblCounter.setStyleSheet(_fromUtf8("color: rgb(170, 0, 0);"))
        self.lblCounter.setObjectName(_fromUtf8("lblCounter"))
        self.lblCounter.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout_2.addWidget(self.lblCounter)
        global lblCounterNumber
        lblCounterNumber = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("DS-Digital"))
        font.setPointSize(350)
        lblCounterNumber.setFont(font)
        lblCounterNumber.setStyleSheet(_fromUtf8("color: rgb(170, 0, 0);"))
        lblCounterNumber.setObjectName(_fromUtf8("lblCounterNumber"))
        lblCounterNumber.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout_2.addWidget(lblCounterNumber)
        self.horizontalLayout_2.addLayout(self.verticalLayout_2)
        self.gridLayout.addLayout(self.horizontalLayout_2, 0, 0, 1, 1)
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 1, 0, 1, 1)
        self.horizontalLayout.addLayout(self.gridLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        global lblNowServingNumber
        global lblCounterNumber
        global lastnum

        f = open('lastnum.txt','r')
        lastnum = f.read()
        if lastnum == None or lastnum == 'None':
            lastnum = 0
            
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.lblNowServing.setText(QtGui.QApplication.translate("MainWindow", "  NOW SERVING  ", None, QtGui.QApplication.UnicodeUTF8))
        self.lblCounter.setText(QtGui.QApplication.translate("MainWindow", "COUNTER", None, QtGui.QApplication.UnicodeUTF8))
        
        lblCounterNumber.setText(str(0))
        lblNowServingNumber.setText(str(lastnum))
        self.val = valChange()
        self.val.start()

class valChange(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)
    def run(self):
        global lblNowServingNumber
        global lblCounterNumber
        global lastnum
        global myval       
        global myctr
        global currentnum
        currentnum = int(lastnum)
        while True:
            
            if myctr == str(1):
               self.s = Bsound()
               self.s.start()
               sleep(0.4)
               currentnum = currentnum + int(myval)
               lblNowServingNumber.setText(str(myval))
               lblCounterNumber.setText(str(myctr))
            
            f = open('lastnum.txt','w')
            f.write(str(que))
            f.close()
            sleep(0.5)
            

            
class Bsound(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)
    def run(self):
            os.system('omxplayer -o local bs2.mp3')
            

if __name__=='__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Ui_MainWindow()
    ex.show()
    sys.exit(app.exec_())
exarg.py

Code: Select all

import mymain
import sys, getopt

def main(argv):
   ctr = ''
   val = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <ctr> -o <val>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <ctr> -o <val>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   mymain.myctr = ctr
   mymain.myval = val

if __name__ == "__main__":
   main(sys.argv[1:])
here's my goal. while the mymain.py is running, i want to access the variable by running the exarg.py into terminal/command line.
here's my command in the terminal:

Code: Select all

sudo python exarg.py -i 1 -o 2
I tried all the possible solution that i know, but no luck. any comments/suggestions would be highly appreciated. Thanks.

User avatar
sommersoft
Posts: 35
Joined: Sat Jul 11, 2015 1:43 pm
Location: Delaware, US

Re: access variable from another python file

Sat Jul 25, 2015 3:29 am

I'm still new to Python, so this may be off the mark: I don't think you're threading correctly. While you have imported mymain.py into exarg.py, I believe you have to include procedures in mymain.py to set cross-thread variables beyond "global myval = val" (which is declared multiple times?). Again, I haven't even begun Python threading attempts, but I've been reading the docs on it. Also, if QtCore handles all of the threading...disregard what I said?

Python Threading doc: https://docs.python.org/3/library/threa ... -threading

Another option: just write them to a file from mymain, and read it with exarg, like your are with "lastnum". You could even use a JSON table, and get rid of the lastnum.txt.

Also, is this Python2 or 3? Whomever corrects my post, will most likely ask this. :P

EDIT:
After some further reading, it seems that you can pass global variables through imported modules. I was thinking more along the lines of concurrent/background processing. Let me keep reading on the import system, and I'll give it another shot. Again, I'm still learning this language, and this is helping me too.
"We mock what we don't understand." - Dr. Trowbridge

akosipolan
Posts: 13
Joined: Sat Jul 19, 2014 7:16 am

Re: access variable from another python file

Mon Jul 27, 2015 2:35 am

sommersoft wrote:I'm still new to Python, so this may be off the mark: I don't think you're threading correctly. While you have imported mymain.py into exarg.py, I believe you have to include procedures in mymain.py to set cross-thread variables beyond "global myval = val" (which is declared multiple times?). Again, I haven't even begun Python threading attempts, but I've been reading the docs on it. Also, if QtCore handles all of the threading...disregard what I said?

Python Threading doc: https://docs.python.org/3/library/threa ... -threading

Another option: just write them to a file from mymain, and read it with exarg, like your are with "lastnum". You could even use a JSON table, and get rid of the lastnum.txt.

Also, is this Python2 or 3? Whomever corrects my post, will most likely ask this. :P

EDIT:
After some further reading, it seems that you can pass global variables through imported modules. I was thinking more along the lines of concurrent/background processing. Let me keep reading on the import system, and I'll give it another shot. Again, I'm still learning this language, and this is helping me too.
thanks for the reply mate.This is my updated codes.

mymain.py

Code: Select all

from PyQt4 import QtCore, QtGui
import PyQt4
import sys
import os
from time import sleep

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        self.showMaximized()
        MainWindow.setStyleSheet(_fromUtf8("background-color: rgb(0, 0, 0);"))
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 2, 0, 1, 1)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.lblNowServing = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Bebas Neue"))
        font.setPointSize(140)
        self.lblNowServing.setFont(font)
        self.lblNowServing.setStyleSheet(_fromUtf8("color: rgb(170, 0, 0);"))
        self.lblNowServing.setObjectName(_fromUtf8("lblNowServing"))
        self.lblNowServing.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout.addWidget(self.lblNowServing)
        self.lblNowServingNumber = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("DS-Digital"))
        font.setPointSize(350)
        self.lblNowServingNumber.setFont(font)
        self.lblNowServingNumber.setStyleSheet(_fromUtf8("color: rgb(170, 0, 0);"))
        self.lblNowServingNumber.setObjectName(_fromUtf8("lblNowServingNumber"))
        self.lblNowServingNumber.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout.addWidget(self.lblNowServingNumber)
        self.horizontalLayout_2.addLayout(self.verticalLayout)
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.lblCounter = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Bebas Neue"))
        font.setPointSize(140)
        self.lblCounter.setFont(font)
        self.lblCounter.setStyleSheet(_fromUtf8("color: rgb(170, 0, 0);"))
        self.lblCounter.setObjectName(_fromUtf8("lblCounter"))
        self.lblCounter.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout_2.addWidget(self.lblCounter)
        self.lblCounterNumber = QtGui.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("DS-Digital"))
        font.setPointSize(350)
        self.lblCounterNumber.setFont(font)
        self.lblCounterNumber.setStyleSheet(_fromUtf8("color: rgb(170, 0, 0);"))
        self.lblCounterNumber.setObjectName(_fromUtf8("lblCounterNumber"))
        self.lblCounterNumber.setAlignment(QtCore.Qt.AlignCenter)
        self.verticalLayout_2.addWidget(self.lblCounterNumber)
        self.horizontalLayout_2.addLayout(self.verticalLayout_2)
        self.gridLayout.addLayout(self.horizontalLayout_2, 0, 0, 1, 1)
        spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        self.gridLayout.addItem(spacerItem, 1, 0, 1, 1)
        self.horizontalLayout.addLayout(self.gridLayout)
        MainWindow.setCentralWidget(self.centralwidget)
        
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        
        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
        self.lblNowServing.setText(QtGui.QApplication.translate("MainWindow", "  NOW SERVING  ", None, QtGui.QApplication.UnicodeUTF8))
        self.lblCounter.setText(QtGui.QApplication.translate("MainWindow", "COUNTER", None, QtGui.QApplication.UnicodeUTF8))        
        self.lblCounterNumber.setText(str(1))
        self.lblNowServingNumber.setText(str(1))

class valChange(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)
    def run(self):
        global myctr
        global myval

        self.lblNowServingNumber.setText(str(myval))
        self.lblCounterNumber.setText(str(myctr))            

if __name__=='__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Ui_MainWindow()
    ex.show()
    sys.exit(app.exec_())
exarg.py

Code: Select all

from PyQt4 import QtCore, QtGui
import mymain
import sys, getopt

def main(argv):
   ctr = ''
   val = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <ctr> -o <val>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <ctr> -o <val>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         ctr = arg
      elif opt in ("-o", "--ofile"):
         val = arg

   m = mymain.valChange()
   m.myctr = ctr
   m.myval = val
   m.start()
       
if __name__ == "__main__":
   app = QtGui.QApplication(sys.argv)
   main(sys.argv[1:])
what i did was, run the mymain.py in the shell and i run the exarg.py in the terminal using this command:

Code: Select all

sudo python exarg.py -i 2 -o 3
and i got an error saying ' QThread: Destroyed while thread is still running'

Return to “Python”