Can't launch multiple local servers using subp

2019-08-20 03:24发布

问题:

I have a list of folders which all contain hugo code for web servers in Windows 7.

Usually I launch them by going into each folder and running the below cmd in cmd prompt:

hugo server -D

What occurs next is, the command outputs messages to the shell, either an error or the local webserver address:

Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender
Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)
Press Ctrl+C to stop

Now I want to launch multiple webservers, which I usually manually do by going into each folder and open cmd prmpt and run the above command.

so I am trying to automate the process as follows:

def launch_sites(site_dir):

    """ 
    testing launching multiple Hugo sites

    site_dir :    root_dir of sites

    """

    sites = [os.path.join(site_dir, site) 
            for site in os.listdir(site_dir)]
    outputs = [] # to get stdout so I can find local web address
    for site in sites:

        if "dummy" in site and os.path.isdir(site):
            os.chdir(site)
            out =subprocess.Popen(f"hugo server -D", stdout = subprocess.PIPE)
            print(out.stdout.read())
            outputs.append(out.stdout)

        else:
            continue

    return outputs

However with the above code, only the first site is launched, and a black screen with the title ("Hugo.exe") pops out. I have to manually close the this black screen, to go through the next iteration in the loop.

Ideally I want to have multiple black boxes (.exes) pop out, so that I know multiple webservers are all running.

How can I solve this problem? Thank you.

A different attempt:

Below you will see two different attempts to try to load multiple instances. However I am only able to get the stdout of the first instance. ONLY Once I close the black box (hugo.exe), I get the stdout of the second instance. If this was done in a non-programming way, when I run the command in different cmd prompts I am able to get an output message right away.

#launch sites

import subprocess
import os
import sys
import threading
import time


def cmd(site):

    os.chdir(site)
    out =subprocess.Popen("hugo server -D", stdout = subprocess.PIPE)
    print('communicate',out.communicate()[0])


def cmd(site):

    os.chdir(site)
    out =subprocess.Popen(['hugo', 'server', '-D'], stdout = subprocess.PIPE)
    print('communicate',out.communicate()[0])


 if __name__ == "__main__":  

    site_dir = r"D:\HUGO DUMMY SITES"
    sites = [os.path.join(site_dir, site) for site in os.listdir(site_dir)]
    for site in sites:
        if "dummy" in site and os.path.isdir(site):
             cmd(site)