将文件输入到praw脚本的Python脚本中

时间:2015-03-19 05:14:50

标签: python settings config praw

所以我有一个简单的reddit bot设置,我使用praw框架编写。代码如下:

import praw
import time
import numpy
import pickle

r = praw.Reddit(user_agent = "Gets the Daily General Thread from subreddit.")
print("Logging in...")
r.login()

words_to_match = ['sdfghm']

cache = []

def run_bot():
    print("Grabbing subreddit...")
    subreddit = r.get_subreddit("test")
    print("Grabbing thread titles...")
    threads = subreddit.get_hot(limit=10)
    for submission in threads:
        thread_title = submission.title.lower()
        isMatch = any(string in thread_title for string in words_to_match)
        if submission.id not in cache and isMatch:
            print("Match found! Thread ID is " + submission.id)
            r.send_message('FlameDraBot', 'DGT has been posted!', 'You are awesome!')
            print("Message sent!")
            cache.append(submission.id)
    print("Comment loop finished. Restarting...")


# Run the script
while True:
    run_bot()
    time.sleep(20)

我想创建一个文件(文本文件或xml,或其他东西),用户可以使用该文件更改要查询的各种信息的字段。例如,我想要一个包含以下行的文件:

Words to Search for = sdfghm
Subreddit to Search in = text
Send message to = FlameDraBot

我希望从字段输入信息,以便它在Words to Search for =而不是整行之后取值。将信息输入文件并保存后。我希望我的脚本从文件中提取信息,将其存储在变量中,并在适当的函数中使用该变量,例如:

words_to_match = ['sdfghm']
subreddit = r.get_subreddit("test")
r.send_message('FlameDraBot'....

所以基本上就像脚本的配置文件一样。如何制作它以便我的脚本可以从.txt或其他适当的文件中获取输入并将其实现到我的代码中?

1 个答案:

答案 0 :(得分:0)

是的,这只是一个普通的Python配置,你can implement in an ASCII file, or else YAML or JSON

创建一个子目录./config,将您的设置放入./config/__init__.py 然后是import config。 使用符合PEP-18的名称,文件./config/__init__.py将如下所示:

search_string = ['sdfghm']
subreddit_to_search = 'text'
notify = ['FlameDraBot']

如果您想要更复杂的配置,请阅读其他许多帖子。

相关问题