python - 在 Google Cloud Compute 实例启动时启动 python 脚本

标签 python google-cloud-platform

我一直在努力寻找在我的云计算实例启动时启动 python 脚本的最佳方式。到目前为止,我还没有让它运行。在实例上手动执行时,脚本会运行。我确实使文件可执行。

这是我目前尝试过的:

1) 使用键“startup-script”将脚本直接添加到元数据。脚本开始于:

#! /usr/bin/python3

后面是脚本内容。

结果: 不会运行,不会显示在日志中。

2) 尝试使用键“startup-script”从元数据执行本地脚本:

#! /usr/bin/bash"
/home/dir/scripts/script.py.

结果: 不会运行,不会显示在日志中。

3) 使用“startup-script-url”指向位于存储桶中的文件。

gs://project.appspot.com/folder/script.py

结果: 不会运行,但会在日志中显示“找到启动脚本”。

希望大家多多指教。

最佳答案

这对我有用:

#! /bin/bash
cat <<EOF > /var/myScriptStackOverflow.py
with open("/var/python_was_here_stack_overflow.txt", "w") as file:
    file.write("Looks that the script is executed")
EOF
python3 /var/myScriptStackOverflow.py

上面的脚本在路径方面是明确的,但这也有效:

#! /usr/bin/python3
with open("/var/python_was_here_stack_overflow.txt", "w") as file:
    file.write("Looks that the script is executed this way as well...")

  • 编辑实例,将上面的脚本粘贴到 Custom metadata 中,键为 startup-script:

enter image description here

  • 重置实例
  • 在实例中使用 ssh 来检查结果:
ls -la /var | grep -i py
-rw-r--r--  1 root root   119 Aug  3 17:33 myScriptStackOverflow.py
-rw-r--r--  1 root root    33 Aug  3 17:33 python_was_here_stack_overflow.txt
cat /var/myScriptStackOverflow.py 
with open("/var/python_was_here_stack_overflow.txt", "w") as file:
    file.write("Looks that the script is executed")
cat /var/python_was_here_stack_overflow.txt 
Looks that the script is executed

关于python - 在 Google Cloud Compute 实例启动时启动 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63232131/

相关文章:

Python 从图中获取所有路径

php - 谷歌云 - 重启后服务器超时

kubernetes - 运行抢占式实例如何保存SQL存储数据?

javascript - 将函数结果分配给变量与调用内联有什么好处?

google-cloud-platform - Cloud Spanner — `SHOW TABLES` 的等效语法?

python - 检查两个顶点是否在 iGraph 中连接

python - 牌组洗牌算法还不够 "human"

python - 将 Raspberry Pi 数据发送到远程服务器

python - 将表单输入的行连接成一行

java - 如何将java项目的maven Artifact 部署/托管到Google Cloud Storage?