Shaanukstar
Shaanukstar

Reputation: 17

How to execute another Python script (Server) but keep the current script running at the same time

I'm making a multiplayer game on Python3. In my main menu screen, when the player clicks play I want the maingame subroutine to run, but also a completely separate file (Server.py) to run in another window parallel to it. Right now I have to open Server.py separately and then the main game file, but I want to be able to open both from the main menu.

I've tried this:

import os
import subprocess

If user_selection == "start":
    command="Server1.py"
    os.system(command)
    subprocess.Popen(command)
    main_game()

The command, os and subprocess parts are supposed to run the server1.py file (which it does). But then it proceeds to run main_game() in the same window so it stops the server and runs the game instead. I've tried using the subprocess command twice (one for server.py and other for main_game.py) but it didn't work. Is there a way when the player clicks "run game" form the main menu screen, the server file executes in a second window and the first window goes from the main menu to the main_game subroutine?

note: both files are in the same directory.

Thanks :)

Upvotes: 0

Views: 610

Answers (1)

zglin
zglin

Reputation: 2919

From the info provided, it seems that concurrent.futures would be the right way to run structure your code. From the python docs

with ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src4.txt', 'dest4.txt')

The code above will copy all of the files simultaneously.

For your code, you would submit both your client and your server to the ThreadPoolExecutor.

Upvotes: 1

Related Questions