首页 > 解决方案 > 如何使用python脚本托管然后访问服务器而不等待返回

问题描述

我正在编写一个创建 html 文件的脚本,然后需要托管它,访问本地主机并截取屏幕截图。我可以让它做所有这些事情,但唯一的问题是它不会尝试截取屏幕截图,直到它从启动服务器的命令获得返回。这意味着服务器将已经关闭。我已经尝试使用 asyncio 解决这个问题,但它似乎仍然不起作用。这是我遇到问题的代码部分:

async def server():
    # host the directory
    await os.system ('python -m http.server')

async def screenshot():
    # cd to google chrome's default install path and call headless chrome from it
    os.chdir("C:\Program Files (x86)\Google\Chrome\Application")
    os.system('chrome  --headless --disable-gpu --enable-logging --screenshot="{}" --window-size=1920,1080 http://localhost:8000/{}'.format(Path(outpath,'images','{}_thumbnail.png'.format(file)),file))
    os.chdir (defaultpath)
    return print ('The image has been saved to {}'.format(str(Path(outpath,'images'))))

loop = asyncio.get_event_loop()

os.chdir(outpath)

asyncio.ensure_future(server())
loop.run_until_complete(screenshot())

await似乎不适用于启动服务器的命令。我也尝试过使用subprocess.call('python -m http.server', creationflags=0x00000008)以及subprocess.call('python -m http.server', creationflags=0x00000010)将服务器托管进程分离到另一个 shell,但 python 在继续之前仍然等待它返回。(作为附带说明,如果您决定测试它们,请小心,因为 0x00000008 在运行时将被隐藏并且很容易忘记)。

有谁知道是否有办法让一个脚本执行此操作,还是在截取屏幕截图时我必须创建第二个应用程序来运行服务器?

标签: pythonserverasync-awaitpython-asyncio

解决方案


考虑使用线程同时运行这两个函数,这样服务器函数就不会阻塞屏幕截图:

from datetime import datetime
import time, threading

def server():
    print("Start Server:", datetime.now())
    time.sleep(5)
    print("Stopped Server:", datetime.now())

def screenshot():
    print("Took Screenshot", datetime.now())

if __name__ == '__main__':
    server_thread = threading.Thread(target=server)
    screenshot_thread = threading.Thread(target=screenshot)

    server_thread.start()
    screenshot_thread.start()

    server_thread.join()
    screenshot_thread.join()

上面打印的:

Start Server: 2018-07-18 01:54:54.409359
Took Screenshot 2018-07-18 01:54:54.409359
Stopped Server: 2018-07-18 01:54:59.410503

您可能还需要延迟屏幕截图函数调用以允许服务器启动,例如,您可以通过延迟粗略地执行此操作。


推荐阅读