2015-03-19 111 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'] 

如果你想更復雜的配置,只是讀了許多其他職位。