はじめに
PythonでTwitterのボットを作ったのだが、print関数で出力したログsystemctl status
コマンドでみることができずはまったので解決方法を覚え書きです。もっといい方法があったら教えていただけると嬉しいです。
環境
CentOS Linux release 8.1.1911 (Core)
Unitファイルの記述
etc\systemd\system\
におくUnitファイルの記述
bot.service
[Unit]
Description=Python Tweet Collector
[Service]
ExecStart=実行ファイル(ここではBotを起動するシェルスクリプト)のパス
Type=simple
StandardOutput=journal #標準出力をjournalctlで見られるようにする
StandardError=journal #標準エラーをjournalctlで見られるようにする
[Install]
WantedBy=multi-user.target
Pythonコマンド実行時のオプション
上記の設定だけだとPythonの標準出力がバッファされてprint文の出力が表示されないことがあるらしい...
ということでシェルスクリプトを書き、そこからBotを起動するようにしました
start_bot.sh
#!/bin/bash
cd $(dirname $0) #このファイルがあるディレクトリに移動
. venv/bin/activate #Pythonの仮想環境を有効化
python -u bot.py # -u オプションでバッファを無効化
最後にchmod 744 start_bot.sh
でシェルスクリプトに実行権限を付与
Botを起動
systemctl start bot.service
Botの状態を確認
systemctl status bot.service
ログを確認
journalctl -u bot.service
Pythonのプリント文で出力した内容がログに表示されているのが確認できると思います
おわり
Linuxのことはまだまだ初心者なので、不適切な箇所の指摘、アドバイス等ありましたらご教授いただけるととてもうれしいです。