2

I have the following:

#! /usr/bin/python3.7
f=open("python_out.txt",'w',encoding='utf-8')
f.write("OK1")
import socket
import telegram
f.write("OK2")
BOT_TOKEN = "telegram BOT_TOKEN"
CHAT_ID = "chat_id"

bot = telegram.Bot(token=BOT_TOKEN)
host_name = socket.gethostname()
content = 'Machine name: %s is shutting down!' % host_name
bot.send_message(chat_id=CHAT_ID, text=content)
f.write("OK3")

I have checked my environment, I can make this script work through python3 script.py when it is in the instance,It can send notifications and output python_out.txt.

I set this script in shutdown-script Screenshot

But when I manually clicked the "stop" button, it did not work as expected. startup-script too. button Screenshot

I have read many posts:

Of course it also includes official documents:

I want to try setting powerbtn.sh,but i can't find /etc/acpi/ in GCP Ubuntu 16.04 LTS

etc ls Screenshot

I can't find any more schedule, any ideas?

baldr
  • 2,891
  • 11
  • 43
  • 61
neslxzhen
  • 75
  • 1
  • 9
  • 1
    Can you try to write your file in `f=open("/tmp/python_out.txt",'w',encoding='utf-8')`? And tell me if it works. If so, I will explain you the issue – guillaume blaquiere Sep 30 '20 at 19:06
  • @guillaumeblaquiere is amazing! After I modify the startup-script and start it, `tmp/python_out.txt` exists, but it only prints to `print(OK1)` https://i.imgur.com/4zoNJg7.png https://i.imgur.com/48wACEf.png https://i.imgur.com/WH9X9Fm.png But I am pretty sure that my environment is correct. When I enter `/usr/bin/python3.7 telegram_notification.py` in the instance connection, it can notify me via telegram, and the content of `telegram_notification.py` is the same as the startup -script same – neslxzhen Oct 01 '20 at 05:50

1 Answers1

1

When you use startup script and shutdown script, the current user that execute is the root user, and the default directory /root/. This directory isn't writable, that's why nothing happens with your code.

Simply write files in writable directory and that's all.

Don't forget that the files that you create are written by the root user and all user can't read and/or write on file wrote by root. Use chmod or chown to change this.

guillaume blaquiere
  • 66,369
  • 2
  • 47
  • 76
  • so why can't it be notified? – neslxzhen Oct 01 '20 at 14:43
  • Agree, it's mentioned for [startup script](https://cloud.google.com/compute/docs/startupscript#running_a_startup_script), and by deduction, I understood that it was also the case for shut down. But, I agree, it's not clead! I opened an issue – guillaume blaquiere Oct 01 '20 at 18:42