简体   繁体   English

Python:提高函数的打印输出错误

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

I am using the InstagramAPI module from this github to create a script that posts pictures at certain time. 我正在使用来自此githubInstagramAPI模块来创建一个在特定时间发布图片的脚本。 A snippet below shows part of the code: 下面的代码段显示了部分代码:

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

This works fine, unless the picture is in the wrong format. 除非图片格式错误,否则此方法可以正常工作。 If it is in the wrong format, nothing is posted and this is printed: 如果格式错误,则不会张贴任何内容,并进行打印:

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

I have a function that will re-size if it isn't in the correct format. 我有一个函数,如果格式不正确,它将重新调整大小。 However, it is just print and not an error. 但是,它只是打印而不是错误。 Therefor, I can not put this in a try/except. 因此,我不能尝试/例外。 So if the file isn't in the right format, it just skips and posts nothing. 因此,如果文件的格式不正确,它只会跳过任何内容,并且不会发布任何内容。

Does anyone know of a way I could have my code save the print output to a variable so I can check if it contains "Uploaded image isn't in the right format" and raise an error if so? 有谁知道我的代码可以将打印输出保存到变量中的方式,以便我可以检查它是否包含“上载的图像格式不正确”,如果存在,则会引发错误?

InstagramAPI.uploadPhoto() returns False if it unsuccessfully tries to post your photo. 如果InstagramAPI.uploadPhoto()尝试发布您的照片失败,则返回False You can do something like: 您可以执行以下操作:

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

This will check to see if it was uploaded successfully, and if not, you can resize the image and try to upload again. 这将检查它是否已成功上传,否则,您可以调整图像大小并尝试再次上传。

In your comment, you say that it returns False regardless of success, but I find that hard to believe. 在您的评论中,您说无论成功如何,它都将返回False,但是我很难相信。 In uploadPhoto() we see this: 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

This will only return False if the response code does not equal 200 or if self.configure() returns a falsey value. 仅当响应代码不等于200或self.configure()返回falsey值时,才返回False。

self.configure() only generates a request body and calls: self.configure()仅生成请求正文并调用:

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

which will return true if your request to the Instagram API was successful: 如果您对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