python - 如何使用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 在运行时将被隐藏并且很容易忘记)。
有谁知道是否有办法让一个脚本执行此操作,还是在截取屏幕截图时我必须创建第二个应用程序来运行服务器?
解决方案
考虑使用线程同时运行这两个函数,这样服务器函数就不会阻塞屏幕截图:
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
您可能还需要延迟屏幕截图函数调用以允许服务器启动,例如,您可以通过延迟粗略地执行此操作。
推荐阅读
- apache - 如何使用 Apache 和 Nginx 安装 ssl 证书
- c++ - “文件系统”不是命名空间类型(C++ 错误
- node.js - 包含空格的 AWS S3 文件
- testing - Testcafe:一份针对多个跑步者的报告
- apache-kafka - 使用列的默认值创建 KSQL 流?
- python - 无法在任何地方运行 jupyter(终端、anaconda 分发器)Mac os 10.12.6
- android - 从 WorkManager 安排警报
- c# - ado.net 实体数据模型未正确使用实体名称
- java - java.lang.IllegalArgumentException:文件不包含有效的私钥:/Users/x/application.key
- runtime-error - 如何为 Mule 域项目创建自定义错误处理程序