2015-03-19 91 views
0

所以我有一个简单的reddit机器人设置,我使用praw框架编写的。代码如下:获取文件输入到Python脚本的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或其他适当的文件获取输入并将其实施到我的代码中?

+0

相关:[Python中的配置文件](http://stackoverflow.com/questions/19078170/python-how-would-you-save-a-simple-settings-config-file/19078712#19078712) – smci 2015-03-19 06:27:34

回答

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'] 

如果你想更复杂的配置,只是读了许多其他职位。