How to call a method from an already running python script
Question: I need to check if the python script is already running then calling a method
from the same running python script. But it must be on same process(pid), no
new process. Is this possible?

I tried some codes but not worked.

    
    
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import Tkinter as tk
    from Tkinter import *
    import socket
    
    
    class Main():
        def mainFunc(self):
            self.root = tk.Tk()
            self.root.title("Main Window")
    
            self.lbl = Label(self.root, text = "First Text")
            self.lbl.pack()
    
            openStngs = Button(self.root, text = "Open Settings", command=self.settingsFunc)
            openStngs.pack()
    
        def settingsFunc(self):
            stngsRoot = Toplevel()
            stngsRoot.title("Settings Window")
    
            changeTextOfLabel = Button(stngsRoot, text = "Change Main Window Text", command=self.change_text)
            changeTextOfLabel.pack()
    
        def change_text(self):
            self.lbl.config(text="Text changed")
    
    # the get_lock from http://stackoverflow.com/a/7758075/3254912
    def get_lock(process_name):
        lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        try:
            print lock_socket
            lock_socket.bind('\0' + process_name)
            print 'I got the lock'
    
            m.mainFunc()
            mainloop()
    
        except socket.error:
            print 'lock exists'
            m.settingsFunc()
            mainloop()
            # sys.exit()
    
    if __name__ == '__main__':
        m=Main()
        get_lock('myPython.py')
    


Answer: You either need:

  * A proactive check in your running process to look at the environment (for instance, the contents of a file or data coming through a socket) to know when to fire the function,
  * or for your running process to receive unix signals or some other IPC (possibly one of the user-defined signals) and perform a function when one is received.

Either way you can't just reach into a running process and fire a function
inside that process (it MIGHT not be literally impossible if you hook the
running process up to a debugger, but I wouldn't recommend it).

`Tkinter` necessarily has its own event loop system, so I recommend reading up
on how that works and how to either run something on a timer in that event
loop system, or set up a callback that responds to a signal. You could also
wrap a non-event loop based system in a try/except block that will catch an
exception generated by a UNIX signal, but it may not be straightforward to
resume the operation of the rest of the program after that signal is caught,
in that case.

