我一直在努力寻找在我的云计算实例启动时启动 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
:
- 重置实例
- 在实例中使用 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/