Скрипт не находит файл при запуске из cmd и не выполняется по расписанию - PullRequest
0 голосов
/ 25 декабря 2018

Создание Reddit-бота (на основе https://www.pythonforengineers.com/build-a-reddit-bot-part-1/). Код обычно работает, следует за вопросами. Файлы сценария и .txt находятся в моей папке LiClipse Workspace (C: \ Users [me] \ Documents \ LiClipse Workspace \Wall_of_Text_Bot) Python находится в отдельном месте, C: \ Users [me] \ AppData \ Local \ Programs \ Python \ Python37

Копия файла praw.ini находится в C: \ Users [me] \AppData \ Roaming. (Это было необходимо, как и раньше, когда при запуске из командной строки praw не смог найти информацию о моем Bot1.)

Вопросы:

  1. Я изменил это дляСоздайте файл времени выполнения, чтобы отслеживать, когда он был запущен. По какой-то причине он не создает файл (запущен ли в LiClipse или где-либо еще). Когда я вручную создал bot_runtimes.txt, он распознает и записывает в этот файл.(Это блоки if и else, которые следуют за импортом в начале.) Есть ли причина, по которой он не создавал файл?

  2. Но если я запускаю из cmd, он нене увидеть или создать файл. Это из-заздесь os.path ищет вещи?Или что-то еще я пропускаю?Бот может найти файл «posts_replied_to» при запуске из cmd, но при запуске из cmd он распечатал «Не было файла среды выполнения бота» (несмотря на то, что файлы ответов и среды выполнения находятся в одном каталоге).

  3. Кажется, я не могу заставить планировщик выполнить сценарий. (Или, может быть, просто не ведутся журналы из-за проблем в 1 и 2?) Я использовал планировщик задач, установил программу как C:\ Users [me] \ AppData \ Local \ Programs \ Python \ Python37 \ python.exe и аргумент "C: \ Users [me] \ Documents \ LiClipse Workspace \ Wall_of_Text_Bot \ Wall_of_Text_Bot.py" Я не получаю никакой ошибкисообщения или даже увидеть командную строку или IDLE всплывающие, когда я принудительно запустить его.

Любая помощь приветствуется. Спасибо.

import praw
# import pdb was in guide file but not used
# import re was in  guide script also not used 
import os
import datetime

import nltk
#nltk.download("punkt")

    #******here are the blocks re: os.path questions*******

if not os.path.isfile('posts_replied_to.txt'):
    posts_replied_to = []
    print("Did't have initial replied to file")
    #working

else:
    with open('posts_replied_to.txt') as f:
        # needed to add variable f for subsequent lines
        posts_replied_to = f.read()
        posts_replied_to = posts_replied_to.split('\n')
        posts_replied_to = list(filter(None, posts_replied_to))
    print("Opened the reply file.")
    #working

if not os.path.isfile('bot_runtimes.txt'):
    bot_runtimes = []
    print("Did't have bot runtimes file")
    #working

else:
    with open('bot_runtimes.txt') as f:
        # needed to add variable f for subsequent lines
        bot_runtimes = f.read()
        bot_runtimes = bot_runtimes.split('\n')
        bot_runtimes= list(filter(None, bot_runtimes))
        print("Opened the runtime file.")

    with open('bot_runtimes.txt', 'a') as f:   
        print(now)
        f.write(now + '\n')
        print("Wrote new run time to the file")

# ****** here is how the bot reads and writes, this works when ran through LiClipse 

subreddit = r.subreddit('pythonforengineers')
for submission in subreddit.hot(limit=5):
    if submission.id not in posts_replied_to:
        print ("Sub ID not in replied file.")

        data = submission.selftext
        words = data.split(" ")
        numwords = len(words)
        lines = data.split("\n")
        numlines = len(lines)

        if numwords > 100 and numlines == 1:
            submission.reply("""Hello, I couldn't help but notice that your submission is a very long paragraph.  Unfortunately, text without paragraph breaks, like yours, is very hard to read.
To help more people read and enjoy your text, please use more paragraph (line) breaks.  If you're not sure where to put them, here are some good resources:

https://www2.open.ac.uk/students/skillsforstudy/dividing-your-work-into-paragraphs.php
http://www.saidsimple.com/content/100835/
http://apps.prsa.org/intelligence/tactics/articles/view/10215/1078/cut_it_down_readers_skip_long_paragraphs#.xbwhavlkjiu

Beep boop.  I'm a bot.  If you think this was in error, you can message me.  I'll probably ignore it.  Beep boop.
            """)
            print('Bot replying type 1 to: ', submission.title)
            posts_replied_to.append(submission.id)
            with open('posts_replied_to.txt', 'w') as f:
                for post_id in posts_replied_to:
                    f.write(post_id + 'type 1' + '\n')

        else:
            for l in lines:
                wordsperline = len(l.split(" "))
                sentencesnltk = len(nltk.sent_tokenize(l))

                if wordsperline > 500 or sentencesnltk > 10:
                    submission.reply("""Hello, I couldn't help but notice that at least one of your paragraphs is very long.  Unfortunately, text without paragraph breaks, like yours, is very hard to read.
To help more people read and enjoy your text, please use more paragraph (line) breaks.  If you're not sure where to put them, here are some good resources:

https://www2.open.ac.uk/students/skillsforstudy/dividing-your-work-into-paragraphs.php
http://www.saidsimple.com/content/100835/
http://apps.prsa.org/intelligence/tactics/articles/view/10215/1078/cut_it_down_readers_skip_long_paragraphs#.xbwhavlkjiu

Beep boop.  I'm a bot.  If you think this was in error, you can message me.  I'll probably ignore it.  Beep boop.
            """)

                    print('Bot replying type 2 to: ', submission.title)
                    posts_replied_to.append(submission.id)
                    with open('posts_replied_to.txt', 'w') as f:
                        for post_id in posts_replied_to:
                            f.write(post_id + 'type 2' + '\n')
...