我在使用Python脚本时经常遇到问题;当我在Pycharm上运行它时,它运行完美,但是当我在计算机的终端上尝试它时,出现以下错误:“发送请求失败:只能转义unicode对象。没有类型。”
我尝试更改PYTHONPATH,但一直收到此错误。这是完整的代码,非常感谢:
import tweepy, re, time
import os
from os import environ
from access import *
from random import randint
def twitter_setup():
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)
return api
def extract_status(path=None):
# No path => return "No book opened!"
if not path:
return "No book opened!"
try:
with open(path, 'r', encoding='utf-8', errors="surrogateescape") as book:
text = book.read()
if text:
return search_sentence(text)
except:
return "Book not found!"
def search_sentence(text):
status = 200
while not (5 < status < 140):
index = randint(0, len(text))
init_index = text[index:].find(".") + 2 + index
last_index = text[init_index:].find(".") + 2 + init_index
status = len(text[init_index:last_index])
sentence = text[init_index:last_index]
sentence = re.sub("\n", " ", sentence)
return sentence
if __name__ == '__main__':
bot = twitter_setup()
segs = 14400
while True:
status = extract_status("texto.txt")
try:
bot.update_status(status)
print ("successfuly posted!")
except tweepy.TweepError as e:
print(e.reason)
time.sleep(segs)
错误消息表明,在将status
字符串传递给update_status()
时,您在文本编码方面遇到一些问题。
除非有特殊原因,否则您可能要尝试从对encoding='utf-8', errors="surrogateescape"
的调用中删除open
,即使用默认的文件打开行为:
with open(path, 'r') as book:
作为补充说明,如果您可以提供Minimal, Reproducible Example来缩小问题范围,这将有助于改善此问题。并且出于可读性目的,请仔细检查您发布的Python代码的缩进。