簡體   English   中英

Python:提高函數的打印輸出錯誤

[英]Python: raising error for print output of function

我正在使用來自此githubInstagramAPI模塊來創建一個在特定時間發布圖片的腳本。 下面的代碼段顯示了部分代碼:

Insta = InstagramAPI(account_name, password)
Insta.login()
InstagramAPI.uploadPhoto(post_path, caption)
InstagramAPI.logout()

除非圖片格式錯誤,否則此方法可以正常工作。 如果格式錯誤,則不會張貼任何內容,並進行打印:

Request return 400 error!
{u'status': u'fail', u'message': u"Uploaded image isn't in the right format"}

我有一個函數,如果格式不正確,它將重新調整大小。 但是,它只是打印而不是錯誤。 因此,我不能嘗試/例外。 因此,如果文件的格式不正確,它只會跳過任何內容,並且不會發布任何內容。

有誰知道我的代碼可以將打印輸出保存到變量中的方式,以便我可以檢查它是否包含“上載的圖像格式不正確”,如果存在,則會引發錯誤?

如果InstagramAPI.uploadPhoto()嘗試發布您的照片失敗,則返回False 您可以執行以下操作:

Insta = InstagramAPI(account_name, password)
Insta.login()
success = Insta.uploadPhoto(post_path, caption)
if not success:
    resizeImage()  # your resize image logic
else:
    Insta.logout()

這將檢查它是否已成功上傳,否則,您可以調整圖像大小並嘗試再次上傳。

在您的評論中,您說無論成功如何,它都將返回False,但是我很難相信。 uploadPhoto()我們看到:

    response = self.s.post(self.API_URL + "upload/photo/", data=m.to_string())
    if response.status_code == 200:
        if self.configure(upload_id, photo, caption):
            self.expose()
    return False

僅當響應代碼不等於200或self.configure()返回falsey值時,才返回False。

self.configure()僅生成請求正文並調用:

return self.SendRequest('media/configure/?', self.generateSignature(data))

如果您對Instagram API的請求成功,它將返回true:

if response.status_code == 200:
    self.LastResponse = response
    self.LastJson = json.loads(response.text)
    return True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM