通过 GCP VM 中的启动脚本运行 python

问题描述 投票:0回答:1

GCP专家!

我在 GCP 上设置了一个 Linux 虚拟机。我想按计划打开和关闭它,当我打开它时,触发我在根目录下的 python 脚本。

当我通过 SSH 执行此操作时,进入虚拟机后,我只需输入

screen -r bot
创建一个虚拟会话,然后在屏幕中输入
main.py
来启动脚本。

你能帮我创建一个执行上述两个步骤的启动脚本吗?

我参考了 GCP 的参考页面,但这并没有帮助我了解如何编写实际的脚本。聊天 GPT 提供了一些选项,但经过几次不同的尝试后,当我通过 SSH 登录虚拟机进行检查时,没有任何内容运行。

https://cloud.google.com/compute/docs/instances/startup-scripts/linux#console

python google-cloud-platform
1个回答
0
投票

您可以使用元数据部分下的启动脚本选项来使GCP虚拟机执行启动脚本。对于您使用屏幕会话的问题,下面的脚本可能会有所帮助。相应地更改您正在使用的 Python 的路径和版本。

startup.sh

#!/bin/bash

# 1. Check if screen session "bot" exists
if ! screen -list | grep -q "bot"; then
  # If not, create a new detached screen session
  screen -dmS bot
fi

SCRIPT_PATH="/path_to_python_script" #Change the path here

# Detach the script from the current terminal

screen -dmS bot bash -c "python3 $SCRIPT_PATH"  #update the python command incase if your using different version

# Print a success message
echo "Python script '$SCRIPT_PATH' started in screen session 'bot'."

exit 0

您可以通过多种方式使用此脚本进行启动,如下官方GCP参考文档所述:

  1. 直接传递启动脚本

  2. 从本地文件传递启动脚本

  3. 从Google云存储传递启动脚本

强烈推荐第一个选项,因为它快速且易于遵循。您可以按照这些文档安排虚拟机启动和停止。

© www.soinside.com 2019 - 2024. All rights reserved.