Bijoy
Bijoy

Reputation: 1131

How to pass a variable from pyqt to .py file and execute it on button click?

I want to pass a filename from this pyqt4 app to another .py file and execute the respective .py file when button is clicked.

GUI.py

from PyQt4 import QtCore, QtGui
import subprocess

class QDataViewer(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QWidget.__init__(self)
            self.uploadButton = QtGui.QPushButton('UPLOAD', self)
            self.uploadButton.setGeometry(300, 20, 80, 35)
            self.Button = QtGui.QPushButton('Key', self)
            self.Button.setGeometry(90, 150, 180, 35)
            self.connect(self.uploadButton, QtCore.SIGNAL('clicked()'), self.open)
            self.Button.clicked.connect(lambda:self.run('My_file.py'))
    def open (self):
        self.filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', "", "*.txt")
        return self.filename # I want THIS VARIABLE to be passed to another python file.

    def run(self, path):
        subprocess.call(['python',path])

My_File.py

textdoc = open(filename_from_GUI(self.filename), 'r').read()
By Using 'textdoc' relevant code(function) here 

I want to know how to first pass self.filename variable from pyqt class to another file and then Execute the My_file.py when self.Button is clicked in GUI.py

Upvotes: 0

Views: 1625

Answers (1)

Aran-Fey
Aran-Fey

Reputation: 43316

You're looking for command line arguments. Change the run function to this:

def run(self, path):
    subprocess.call(['python',path,self.filename])

to pass the file name as a command line argument. In file My_file.py you can then access it like so:

import sys
print(sys.argv[1])

Upvotes: 2

Related Questions