【问题标题】:Getting file input into Python script for praw script为 praw 脚本获取文件输入到 Python 脚本中
【发布时间】:2015-05-22 03:46:02
【问题描述】:

所以我有一个简单的 reddit 机器人设置,我使用 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_match = ['sdfghm']
subreddit = r.get_subreddit("test")
r.send_message('FlameDraBot'....

所以基本上就像脚本的配置文件。我该如何着手使我的脚本可以从 .txt 或其他适当的文件中获取输入并将其实现到我的代码中?

【问题讨论】:

标签: python settings config praw


【解决方案1】:

是的,这只是一个普通的旧 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']

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

【讨论】:

    猜你喜欢
    • 2020-09-21
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 2017-11-07
    • 2012-02-01
    相关资源
    最近更新 更多