簡體   English   中英

Tmux,cron 不適用於我在谷歌雲上的 python 腳本

[英]Tmux, cron doesn't work with my python script on google clouds

所以我試圖使用谷歌雲機器 24/7 運行我的 python 腳本,我想使用 tmux 和 cron,但我認為我做錯了什么,它對我不起作用。 當我在 SSH 窗口中運行我的腳本時,它運行良好,但是當我關閉它時。 它不會發布到 Twitter 或編輯我的 json 文件。

我嘗試在 google 中尋找答案,但對我來說沒有運氣。 我曾嘗試使用 tmux 並以無限循環且無鎖的方式運行我的腳本。 我嘗試使用沒有無限循環的 cron 並每 5 分鍾運行一次我的腳本,但沒有成功。 我曾嘗試在 tmux 中使用 cron,但沒有成功。

import requests
import json
import time
import twitter

class TodayILearned():
    def __init__(self):
        self.link = 'https://www.reddit.com/r/todayilearned/new/.json'

    def get_info(self):
        try:
            r = requests.get(self.link, headers = {'User-agent': 'your bot 0.1'})
            r.raise_for_status()
        except requests.exceptions.HTTPError as error:
            print(f'There is problem:\n{error}')
            return False
        new_til = json.loads(r.content)
        new_til = new_til["data"]["children"][0]['data']['title']
        new_til = new_til.replace('TIL', '').replace('Til', '').strip()
        for _ in range(len(new_til) - 1):
            if new_til[0].isalpha() == False:
                new_til = new_til.replace(new_til[0], '').strip()#.capitalize()
            else:
                break
        new_til = new_til.split(' ', 1)
        if new_til[0].lower() == 'this' or new_til[0].lower() == 'that' or new_til[0].lower() == 'about' or new_til[0].lower() == 'of':
            new_til.pop(0)
        new_til = ' '.join(new_til)
        new_til = new_til[:1].upper() + new_til[1:]
        if new_til[-1].isalnum() == True:
            new_til += '.'
        return new_til if len(new_til) < 280 else False #change for 140 when twitter working 

    def save_new_dict(self, new_dict):
        with open('til_news_base.json', 'w') as json_file:
            json.dump(new_dict, json_file, indent=2)

    def read_json_file(self):
        with open('til_news_base.json') as json_file:
            data = json.load(json_file)
        self.last_key = int(sorted(list(data.keys()))[-1])
        return data

    def post_on_twitter(self, new_post):
        TOKEN = 'xxx'
        TOKEN_KEY = 'xxx'
        CON_SEC = 'xxx'
        CON_SEC_KEY = 'xx'
        my_auth = twitter.OAuth(TOKEN,TOKEN_KEY,CON_SEC,CON_SEC_KEY)
        twit = twitter.Twitter(auth=my_auth)
        twit.statuses.update(status=new_post)

    def program(self):
        wait_for_seconds = 30
        while True:
            #first load the base from file
            dict_with_news = self.read_json_file()
            #second get new posts from reddit
            new_info = self.get_info()
            #check if new post in base or if is it last post
            if new_info != False:
                if new_info != dict_with_news[str(self.last_key)]:
                    dict_with_news[str(self.last_key + 1)] = new_info
                    print(new_info)
            #add to base if not
                    self.save_new_dict(dict_with_news)
            #print new TIL on twitter
                    self.post_on_twitter(new_info)
            #wait Xs
            time.sleep(wait_for_seconds)


def program():
    class_til = TodayILearned()
    class_til.program()

if __name__ == "__main__":
    program()

我希望它每 5 分鍾運行一次,但沒有運氣,在我關閉 SSH 后它不會向 Twitter 發布新內容。 在打開與谷歌雲的 SSH 連接后,我寫道:tmux,將目錄更改為我的 python 文件和 json 文件所在的位置。 我使用 python3 運行我的 python 腳本。 我可以在控制台中看到我的新消息,也可以在 twitter 上看到。 我等了 5 分鍾,每次在 reddit 上發布新內容時,我都可以在控制台中看到它並發布在 twitter 上。 我關閉了我的 SSH,在 twitter 或 json 文件中沒有新帖子。 我再次打開 SSH,沒有錯誤或任何東西。 我也嘗試了 cron:我使用了命令 '*/5 * * * * python 3 /python_programs/watch_for_new_TIL_facts.py',當然沒有 ''。 仍然沒有運氣。 我在 tmux 的 cron 中嘗試了這個命令,沒有它。 我以普通用戶和 root 身份創建了東西。

在您的 crontab 中,您在Python3之間有一個空格。 消除它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM