Setting a python script default when creating a new file - python

I would like to set a default custom script whenever creating a new .py file or .ipynb file in Pycharm or VS Code.
I would like the default script to load looking as such:
import time
import datetime
start = time.time()
# Code here.
end = time.time()
print(str(datetime.timedelta(seconds=end - start)))
Is it possible to set default scripts in IDEs? Many Thanks.

It is currently not possible to set a new file template. Maybe the code snippet will help you.
You can easily define your own snippets without any extension. To create or edit your own snippets, select User Snippets under File > Preferences (Code > Preferences on macOS), and then select the language (by language identifier) for which the snippets should appear, or the New Global Snippets file option if they should appear for all languages. VS Code manages the creation and refreshing of the underlying snippets file(s) for you.
Of course, we choose python here
Then change the open file to the following.
{
"time":{
"prefix": "time",
"body": [
"import time",
"import datetime",
"start = time.time()",
"$1",
"end = time.time()",
"print(str(datetime.timedelta(seconds=end - start)))"],
"description": "",
"isFileTemplate": true
}
}
Then enter time in the .py file to get the fragment.
More information about the code snippet can be found here.

Related

How do i remove the unnecessary text in the terminal in vscode?

Hi i'm new into vscode and when i run a program there is some text that i want to get rid of.
i mainly want to remove the first two paragraphs, but also removing the path would be ideal
i tried code runner but thats not the solution i'm looking for
i also tried changing the color to black but i reckon there is a way to remove it
Adding the "-NoLogo" start parameter will remove the paragraph of text; If you open your settings file (Ctrl+Shift+P and then type "Settings" -> User Settings JSON), you can use the following bit of configuration:
// should go in the main JSON object with the other keys
"terminal.integrated.profiles.windows": {
// it might generate some more profiles automatically, but powershell is what matters
"PowerShell": {
"source": "PowerShell",
"icon": "terminal-powershell",
"args": ["-NoLogo"]
}
}
I believe by default those lines will always appear because those are the one that show up when you open cmd on Windows.
Also, by default, the path open to the current project folder, that the reason why you see the path.
You can do a cls to clear the terminal, but the path will remain unless you change the directory.
You can read more about VS Code integrated terminal here and about terminal profiles here
First go to terminal settings and then the add -nologo arg

I'm using same py file in VS Code to learn different examples. Why does it still run the first block of code after I delete and write different code?

I started with this example:
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
I deleted this and moved on to a new example, within same py file:
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
After I click run on this second code, VS Code still prints the output for the cars example. What could be the matter?
The white dot indicates the file has not been saved.
You can add this in the settings.json file:
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000,
to enable the autosave function in the VSCode.
The issue is unlikely to be due to the code you've written. It is likely related to how you're saving your .py file, and how it is being ran.
Are you running the file using the 'play' button / Ctrl+F5 in VSCode, or are you double clicking on the .py file from File Explorer / Finder?
If it's the latter, then perhaps you're not saving the file in VSCode first, try saving the file with Ctrl+S first.
Screenshots would likely go a long way to helping you answer this question.
Command n (New file..), convert language mode to python from plain text and paste the new block and run ?

How to write OS X Finder Comments from python?

I'm working on a python script that creates numerous images files based on a variety of inputs in OS X Yosemite. I am trying to write the inputs used to create each file as 'Finder comments' as each file is created so that IF the the output is visually interesting I can look at the specific input values that generated the file. I've verified that this can be done easily with apple script.
tell application "Finder" to set comment of (POSIX file "/Users/mgarito/Desktop/Random_Pixel_Color/2015-01-03_14.04.21.png" as alias) to {Val1, Val2, Val3} as Unicode text
Afterward, upon selecting the file and showing its info (cmd+i) the Finder comments clearly display the expected text 'Val1, Val2, Val2'.
This is further confirmed by running mdls [File/Path/Name] before and after the applescript is used which clearly shows the expected text has been properly added.
The problem is I can't figure out how to incorporate this into my python script to save myself.
Im under the impression the solution should* be something to the effect of:
VarList = [Var1, Var2, Var3]
Fiele = [File/Path/Name]
file.os.system.add(kMDItemFinderComment, VarList)
As a side note I've also look at xattr -w [Attribute_Name] [Attribute_Value] [File/Path/Name] but found that though this will store the attribute, it is not stored in the desired location. Instead it ends up in an affiliated pList which is not what I'm after.
Here is my way to do that.
First you need to install applescript package using pip install applescript command.
Here is a function to add comments to a file:
def set_comment(file_path, comment_text):
import applescript
applescript.tell.app("Finder", f'set comment of (POSIX file "{file_path}" as alias) to "{comment_text}" as Unicode text')
and then I'm just using it like this:
set_comment('/Users/UserAccountName/Pictures/IMG_6860.MOV', 'my comment')
After more digging, I was able to locate a python applescript bundle: https://pypi.python.org/pypi/py-applescript
This got me to a workable answer, though I'd still prefer to do this natively in python if anyone has a better option?
import applescript
NewFile = '[File/Path/Name]' <br>
Comment = "Almost there.."
AddComment = applescript.AppleScript('''
on run {arg1, arg2}
tell application "Finder" to set comment of (POSIX file arg1 as alias) to arg2 as Unicode text
return
end run
''')
print(AddComment.run(NewFile, Comment))
print("Done")
This is the function to get comment of a file.
def get_comment(file_path):
import applescript
return applescript.tell.app("Finder", f'get comment of (POSIX file "{file_path}" as alias)').out
print(get_comment('Your Path'))
Another approach is to use appscript, a high-level Apple event bridge that is sadly no longer officially supported but still works (and saw an updated release in Jan. 2021). Here is an example of reading and setting the comment on a file:
import appscript
import mactypes
# Get a handle on the Finder.
finder = appscript.app('Finder')
# Tell Finder to select the file.
file = finder.items[mactypes.Alias("/path/to/a/file")]
# Print the current comment
comment = file.comment()
print("Current comment: " + comment)
# Set a new comment.
file.comment.set("New comment")
# Print the current comment again to verify.
comment = file.comment()
print("Current comment: " + comment)
Despite that the author of appscript recommends against using it in new projects, I used it recently to create a command-line utility called Urial for the specialized purpose of writing and updating URIs in Finder comments. Perhaps its code can serve as an an additional example of using appscript to manipulate Finder comments.

sublime - save all open/loaded files that have names?

In Sublime Text 2, I want to be able to save all open/loaded files that have names.
I like how Sublime can have files with filenames, and have files that were never saved, and can be closed and it remembers about the untitled files and reloads them without me having to save them.
But when a file has a filename and has some changes in the buffer not yet saved, sublime shows it as such, with the filename and circle, I close sublime, and reopen it, I sublime has remebered it as it was and so the changes are still not saved to the file. That's great.. But.. I'd like a command to save all, but not the untitled ones.
There is a save all option in the menu, but it pops up a dialog box asking regarding saving of untitled files.
What API functions would be involved to write a command that leaves the untitled ones as is, and saves the ones with filenames? (and is there any example code I can run that uses those API functions?)
AFAIK, an opened file is represented by one or more views. So try to get all views and save those with file names. I wrote a simple example. Hope it can help you.
By the way, you can check all API's via the following link.
Sublime Text 2 API Reference
import sublime, sublime_plugin
class SaveAllExistingFilesCommand(sublime_plugin.ApplicationCommand):
def run(self):
for w in sublime.windows():
self._save_files_in_window(w)
def _save_files_in_window(self, w):
for v in w.views():
self._save_exiting_file_in_view(v)
def _save_exiting_file_in_view(self, v):
if v.file_name():
if v.is_dirty():
v.run_command("save")
lhuang's answer is fantastic, and does exactly what I think you want it to do. Make sure you save the plugin as Packages/User/save_all_existing_files.py in order for it to work properly. You can reach the Packages directory via the Preferences -> Browse Packages... menu item. I do have a few additions to make your life a little easier, though - a menu item and a key combination.
You generally shouldn't edit anything in the Packages/Default directory, as all the files can be overridden/expanded upon, but in this case I recommend it for aesthetics sake. Open Packages/Default/Main.sublime-menu and add the following line right after line 128, which should be the save_all menu item:
{ "command": "save_all_existing_files", "caption": "Save All Named Files", "mnemonic": "F" },
This will add a "Save All Named Files" option to the File menu. Next, go to Preferences -> Key Bindings - User and add the following line:
{ "keys": ["ctrl+alt+shift+s"], "command": "save_all_existing_files" },
If this file doesn't have any other contents, surround the above line with square brackets [ ] and remove the trailing comma, otherwise Sublime will complain at you.
Once the keymap file is saved, you can trigger the command by hitting CtrlAltShiftS. Obviously, you can change the keys if you don't like them. If you pick a combination that gives weird behavior, check out the FindKeyConflicts plugin by #skuroda - it's invaluable for troubleshooting your setup, and especially when developing your own packages.
Good luck!
Just add the next line to the Preferences > Key Bindings - User
{ "keys": ["super+shift+s"], "command": "save_all" }
super is a Command key in OS X. Use ctrl on Windows.

How to display line numbers in IPython Notebook code cell by default

I would like my default display for IPython notebook code cells to include line numbers.
I learned from Showing line numbers in IPython/Jupyter Notebooks that I can toggle this with ctrl-M L, which is great, but manual. In order to include line numbers by default, I would need to add something to my ipython_notebook_config.py file. Unless I've missed something, there is not an explanation of how to do this in the documentation.
(For Jupyter 4+) In the latest Jupyter versions, they have documented the place to make config changes. So basically, in the Jupyter update, they've removed the concept of profiles, so the custom.js file location is now .jupyter/custom/custom.js, depending on where your .jupyter folder is. So if you don't have a custom folder or the custom.js file, just create them, then put these lines into the newly created file:
define([
'base/js/namespace',
'base/js/events'
],
function(IPython, events) {
events.on("app_initialized.NotebookApp",
function () {
require("notebook/js/cell").Cell.options_default.cm_config.lineNumbers = true;
}
);
}
);
The above is for setting line numbers to all your cell types at the same time. Code, Markdown and Raw cells will all get line numbers if you do this. If you want line numbers only for code cells, there is a simpler approach. Select a code cell, open the Chrome/Firefox JavaScript console, type the following lines:
var cell = Jupyter.notebook.get_selected_cell();
var config = cell.config;
var patch = {
CodeCell:{
cm_config:{lineNumbers:true}
}
}
config.update(patch)
Then reload the page. These changes persist because Jupyter will create a json config file in .jupyter/nbconfig to store them. This method is from this page of the documentation, so read the docs for more config changes that you can make.
(old answer)
In the latest version of IPython Notebook (v3.1.0), go to ~/.ipython/<profile_name>/static/custom/custom.js and add these lines:
define([
'base/js/namespace',
'base/js/events'
],
function(IPython, events) {
events.on("app_initialized.NotebookApp",
function () {
IPython.Cell.options_default.cm_config.lineNumbers = true;
}
);
}
);
The IPython.Cell.options_default.cm_config.lineNumbers = true; line alone will not work as it needs to load the IPython.Cell object before it tries this. Adding this line alone will cause an undefined error in the console. You need to encase it in the event handler as shown.
#William-Denman's code might have worked for an earlier version, but now you will need to do this.
EDIT: The line of code right in the middle has to be changed to require("notebook/js/cell").Cell.options_default.cm_config.lineNumbers = true; for the latest version of IPython/Jupyter (IPython 4.0.0, Jupyter 4.0.6). The old IPython.Cell object will also work, but your web console will throw a deprecation warning, so you can expect the old line to not be supported in future versions.
Also, in the latest IPython/Jupyter, which I'm running using the WinPython portable, I couldn't find the custom.js file within the profile folder. I found it (after much searching) in WinPython-64bit-2.7.10.3\python-2.7.10.amd64\Lib\site-packages\notebook\static\custom. I don't know if this is a WinPython thing or a Jupyter thing. If someone has Jupyter (latest version) installed normally (using pip or whatever) and can still find the custom.js file in the profile folder, please comment.
In your custom.js file (location depends on your OS) put
IPython.Cell.options_default.cm_config.lineNumbers = true;
If you can't find custom.js, you can just search for it, but generally it will be in your profile_default folder. If it doesn't exist, create the file at $(ipython locate profile)/static/custom/custom.js
If for whatever reason that doesn't work, you can always edit the custom.js file in the site-packages/IPython/html/static/custom/ in the same way.
Above didn't work for me in 2018
I found that inside ~/.jupyter/nbconfig/notebook.json I needed to add to add the following lines:
"CodeCell": {
"cm_config": {
"lineNumbers": true
}
inside the object that was there. So the final object would look like:
{
"CodeCell": {
"cm_config": {
"lineNumbers": true
}
}
}

Categories