I've been trying to find the best way to start a python script on startup of my cloud compute instance. So far, I haven't gotten it to run. The script does run when manually executed on the instance. I did make the file executable.
This is what I have tried so far:
1) Add script directly to metadata with key "startup-script". Script starts with:
#! /usr/bin/python3
Followed by the script contents.
Result: Won't run, doesn't show up in log.
2) Try to execute local script from metadata with key "startup-script":
#! /usr/bin/bash"
/home/dir/scripts/script.py.
Result: Won't run, doesn't show up in log.
3) Point to file located in storage bucket with "startup-script-url".
gs://project.appspot.com/folder/script.py
Result: Won't run, but shows "Found startup script" in log.
I hope anyone has some insights.
This worked for me:
#! /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
The script above is explicit in respect to the paths, but this also works:
#! /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 with the key startup-script:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With