I am currently using the application Canopy produced by Enthought and I have the requirement that each file I make has to contain a comment at the top saying who the author is, when the file was created and when it was last edited.
I would like to know if there is a way that when I create a new file in Canopy (specifically a python file) it can automatically populate the file with this information at the top. Similarly if I were to re-open the file after it had been saved, or upon each new save it would automatically update the relevant last edited part of the comment with a new datetime stamp.
I have been advised by the Enthought application to submit my question to Stackoverflow so I hope it is appropriate.
Yes it is the right place to ask questions.
The way canopy allows you to do this and a lot of other customizations like that is by using the macro recorder. With canopy open, select Tools > Record macro. Type a name for that macro, something like new_file_with_header
. Then click in the code editor, and ctrl-n
or cmd-n
to create a new file and type whatever you want at the top. Then, tools > stop macro recording and then Tools > edit macro. You should find the new one you created and double-clicking on it should show you the code that it will run if you execute it. I did it with just writing # Hello world
and got:
# -*- coding: utf-8 -*-
def run():
code_task = get_active_task()
code_task.new_file(factory_id='canopy.editor.code_editor', editor_type='Python')
code_editor = code_task.active_editor
cursor = code_editor.cursor
cursor.write(u'# Hello world')
code_editor.autoindent_newline()
The good news is that this is plain python, so if you wanted to add the date of today, you can modify it similar to that:
# -*- coding: utf-8 -*-
import datetime
def run():
code_task = get_active_task()
code_task.new_file(factory_id='canopy.editor.code_editor', editor_type='Python')
code_editor = code_task.active_editor
cursor = code_editor.cursor
cursor.write(u'# Hello world %s' % datetime.datetime.now().strftime("%H-%M-%S"))
code_editor.autoindent_newline()
Ultimately, assign a keybinding that is not already in use and off you go.