I want to be able to check if the working .blend file has been saved when a user presses a button. If it has not been, Blender should give an error.
I just want the user to save before running my add-on.
I want to be able to check if the working .blend file has been saved when a user presses a button. If it has not been, Blender should give an error.
I just want the user to save before running my add-on.
If 'the file' you are referencing is a blender file and you want to know if it has been saved then there are two properties you can check.
If a blender file hasn't been saved at all you can check it's is_saved property as this will be False if it hasn't been saved:
if bpy.data.is_saved:
#File has been saved. Do something.
(A previous version of this answer instead checked if the filepath property was blank instead - the above is a correction thanks to poor's comment).
For files that have been saved you can check the is_dirty property, which will be True when changes have been made since the last save:
if bpy.data.is_dirty:
#Changes have been made since the last save. Do something.
To get a button to execute code have a look at Simple way to add button to UI.
For error messages look at Proper way to show users error info in the UI for addons.
is_saved flag is probably the better option to check if the file is saved - Has the current session been saved to disk as a .blend file If you really like to go with filepath the comparison operator is not necessary here. You can write if not bpy.data.filepath: to check an empty string, that's easier to understand and more pythonic: http://stackoverflow.com/a/9573259/3091066
– p2or
Jul 29 '16 at 16:00
Just to make Ray's answer more specific with my question:
The code should be
if bpy.data.is_dirty:
print("You must save your file!")
else:
print("File OK!")
This isn't really a blender question, but more a python question. But anyway, this would do the trick:
from os.path import isfile
if not isfile( PathOfSavedFile ): # Check if file exists
raise IOError( "file <%s> not saved" % PathOfSavedFile )