简体   繁体   中英

Python script trigger a method in another script

I have two scripts say script1.py on PC1 and script2.py on PC2. Now, script1.py has two methods as shown below. The method1() on PC1 must be completed before method2() on PC2 can be executed. So, how can I trigger method2() of script2.py on PC2 which is already running?

I can split script2.py into two different .py files ie method1.py and method2.py on PC2 and call method2.py after script1_method2() on PC1 has finished but then I need to pass the foo object to it. Maybe I can pickle the foo object and read it from a file?

Is there a better way to go about this?

Note: I can communicate between PC1 and PC2 using paramiko ssh

def script1_method1():
    """
    This is on PC1
    get connection from PC2 script 2 and do some work
    """
    pass

def script1_method2():
    """
    This is on PC1
    work which needs some time
    only after this work is done, call PC2 script2
    """
    pass

def script2_method1():
    """
    This is on PC2
    create an object 'foo' which connects to PC1 script1
    return object 'foo' to main
    """
    pass



def script2_method2(foo):
    """
    This is on PC2
    get object 'foo' and do some work with it
    """
    pass

If you can mount PC2 dir with script2.py (for example via sshfs) you can add this dir to PYTHONPATH, then write a simple program:

from script1 import *
from script2 import *

script1_method1()
script2_method1()
script1_method2()
script2_method2()

This is a classical IPC question. Because you have run those script between two Machine, the Socket should be a good option. and you can run method1 and then send something to the PC2 by socket , to do that your method2 have to register in poll. like epoll . There are also many good blogs show you how to use it by Python , like this . If you know good at event driver mode , the multi-thread mode is another good option to wait the trigger occur.

It seems like you are setting up a message broker / shared task queue between two PC's.

If you can communicate between PC's using ssh, I'd suggest either setting up a simple HTTP server on each machine and sending a POST message with the data via curl to localhost:8000/:script_name, or communicating with the process via a unix socket .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM