Open sublime-project file programmatically - python

I'm currently writing a plugin for Sublime Text 3, which aims to offer the user a more flexible session management.
As it seems the API doesn't offer a way to open a .sublime-project file. I'm obviously able to open files as usual - using window.open_file - but not to tell Sublime to open a specific project file.
It will just open it in a new tab, which isn't exactly what I was hoping for.
I'm able to access and set the project_data using window.project_data and window.set_project_data, but while there is a window.project_file_name method it has no counterpart.
This is problematic since the project_data often contains relative paths, which need to be interpreted relative to the .sublime-project files location. If I just dump the data as found into a new window (set_project_data), all relative paths will be interpreted as relative to root (at least on my Ubuntu system).
I can handle the relative paths myself and modify the project_data accordingly but that's hacky.
Is there any undocumented method or something I missed?
EDIT: The plugin in question.

Try to open the file with suffix ':1' - meaning 'line number #1':
This works for me:
$ subl projectname.sublime-project:1

Found a method to do this in a Sublime Plugin called ProjectManager. You'll find the code in this file...
https://github.com/randy3k/ProjectManager/blob/master/pm.py
# Code lifted from https://github.com/randy3k/ProjectManager/blob/master/pm.py
def subl(args=[]):
# learnt from SideBarEnhancements
executable_path = sublime.executable_path()
if sublime.platform() == 'linux':
subprocess.Popen([executable_path] + [args])
if sublime.platform() == 'osx':
app_path = executable_path[:executable_path.rfind(".app/") + 5]
executable_path = app_path + "Contents/SharedSupport/bin/subl"
subprocess.Popen([executable_path] + args)
if sublime.platform() == "windows":
def fix_focus():
window = sublime.active_window()
view = window.active_view()
window.run_command('focus_neighboring_group')
window.focus_view(view)
sublime.set_timeout(fix_focus, 300)
subl(project_file) # The something.sublime-project file.

Related

How do I create a shortcut to a folder? [duplicate]

I have created shortcuts for executables and it works, but when I try to create one for a folder it does not work.
It does create a shortcut, it is just not the right 'Target Type'. Please take a look at the image below.
Instead of 'File', the target type should be 'File folder'. The problem is that when I open the shortcut it asks me which program do I want to open the File with and it does not open the folder.
The function I'm using to create the shortcuts is the following
from win32com.client import Dispatch
import winshell
import os
def create_shortcuts(self, tool_name, exe_path, startin, icon_path):
shell = Dispatch('WScript.Shell')
shortcut_file = os.path.join(winshell.desktop(), tool_name + '.lnk')
shortcut = shell.CreateShortCut(shortcut_file)
shortcut.Targetpath = exe_path
shortcut.WorkingDirectory = startin
shortcut.IconLocation = icon_path
shortcut.save()
I don't know if it's possible to set the 'Target Type'. I couldn't find a way to do it, but I do know there must be a way.
If you want to use .Net "clr" (especially if you already require it):
First run this... you will have to ship the output of this command with your application:
"c:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\TlbImp.exe" %SystemRoot%\system32\wshom.ocx /out:Interop.IWshRuntimeLibrary.dll
tlbimp.exe might even be in the path if you installed the Windows SDK in a fairly standard way. But if not, it's OK, you'll just ship the "assembly" (fancy word for interface-providing dll in .Net land) with your application.
Then this code will work in python:
import clr
sys.path.append(DIRECTORY_WHERE_YOU_PUT_THE_DLL)
clr.AddReference('Interop.IWshRuntimeLibrary')
import Interop.IWshRuntimeLibrary
sc = Interop.IWshRuntimeLibrary.WshShell().CreateShortcut("c:\\test\\sc.lnk")
isc = Interop.IWshRuntimeLibrary.IWshShortcut(sc)
isc.set_TargetPath("C:\\")
isc.Save()
.... the above code, with far too much modification and preamble, might even work with Mono.
For future reference: I observed the described behavior in python 3.9.6 when creating a shortcut to a non-existing directory, which was easily fixed by incorporating os.makedirs() into the method.
I've added a method parameter to the version I'm using, so it can handle shortcuts to files and directories:
def create_shortcuts(self, tool_name, exe_path, startin, icon_path, is_directory=False):
if is_directory:
os.makedirs(exe_path, exist_ok=True)
shell = Dispatch('WScript.Shell')
shortcut_file = os.path.join(winshell.desktop(), tool_name + '.lnk')
shortcut = shell.CreateShortCut(shortcut_file)
shortcut.Targetpath = exe_path
shortcut.WorkingDirectory = startin
shortcut.IconLocation = icon_path
shortcut.save()

Methods to avoid hard-coding file paths in Python

Working with scientific data, specifically climate data, I am constantly hard-coding paths to data directories in my Python code. Even if I were to write the most extensible code in the world, the hard-coded file paths prevent it from ever being truly portable. I also feel like having information about the file system of your machine coded in your programs could be security issue.
What solutions are out there for handling the configuration of paths in Python to avoid having to code them out explicitly?
One of the solution rely on using configuration files.
You can store all your path in a json file like so :
{
"base_path" : "/home/bob/base_folder",
"low_temp_area_path" : "/home/bob/base/folder/low_temp"
}
and then in your python code, you could just do :
import json
with open("conf.json") as json_conf :
CONF = json.load(json_conf)
and then you can use your path (or any configuration variable you like) like so :
print "The base path is {}".format(CONF["base_path"])
First off its always good practise to add a main function to go with each class to test that class or functions in the file. Along with this you determine the current working directory. This becomes incredibly important when running python from a cron job or from a directory that is not the current working directory. No JSON files or environment variables are then needed and you will obtain interoperation across Mac, RHEL and Debian distributions.
This is how you do it, and it will work on windows also if you use '\' instead of '/' (if that is even necessary, in your case).
if "__main__" == __name__:
workingDirectory = os.path.realpath(sys.argv[0])
As you can see when you run your command, the working directory is calculated if you provide a full path or relative path, meaning it will work in a cron job automatically.
After that if you want to work with data that is stored in the current directory use:
fileName = os.path.join( workingDirectory, './sub-folder-of-current-directory/filename.csv' )
fp = open( fileName,'r')
or in the case of the above working directory (parallel to your project directory):
fileName = os.path.join( workingDirectory, '../folder-at-same-level-as-my-project/filename.csv' )
fp = open( fileName,'r')
I believe there are many ways around this, but here is what I would do:
Create a JSON config file with all the paths I need defined.
For even more portability, I'd have a default path where I look for this config file but also have a command line input to change it.
In my opinion passing arguments from command line would be best solution. You should take a look at argparse . This allows you to create nice way to handle arguments from the command line. for example:
myDataScript.py /home/userName/datasource1/

How can I directly open a custom file with python on a double click?

I am programming on a windows machine and I have an app that reads file selected by the user. Is it possible to allow them to open the file directly when they double click. This needs to work when the program is "compiled" as an .exe with cxfreeze.
What I am really asking is this:
Is there a way to allow the user to double click on a custom file (.lpd) and when they do windows starts the program (a compiled cxfreeze .exe) and passes it the file path as an argument.
The only way Windows associates files with a particular program is by their extension, so this only works if your files have a unique extension (which it looks like maybe they do). So your user would need to setup the association on their machine, which varies depending on the version of Windows. For instance, in Windows 7 it would probably be through Control Panel\All Control Panel Items\Default Programs\Set Associations.
It is possible for you to automatically setup this association on their system (probably by editing the Windows registry), but that would generally be done during an installation, and you should ask the users permission to do this first.
I used PyInstaller for exe-generation.
Here is a small example:
import sys
class Test():
def __init__(self, path=None):
super().__init__()
self.path = path
def start(self):
if self.path == None:
pass
else:
print(self.path)
if __name__ == '__main__':
if len(sys.argv) > 1 :
mytest = Test(sys.argv[1])
else:
mytest = Test()
mytest.start()

Open specific file type with Python script?

How can I make a Python script to be a specific file type's (e.g., *.foo) default application? As in, when I double click the file in the Finder / Explorer I want the file to open in the Python script.
Is this possible to do in Win and/or OS X? The application is a PySide app if that matters.
Mac OS X
On Mac OS X you can use Automator to create an application that calls your python app and passes the input file path as a string argument. In the application workflow wizard, add action "Run Shell Script", select Pass input: as as arguments, and in the text box add:
python /path/to/my/app/myapp.py "$#"
The "$#" passes along whatever arguments were in the input (aka the selected file) as strings. As long as your script is set up to deal with the input (sys.argv) as a list of strings (the first one being the python app path), then it will work.
When you save that Automator workflow, it is treated by OS X like any other app, and you can set that app as the default for files of type "*.foo". To associate "*.foo" with that app, right click a .foo file, Get Info, Open with: Other..., choose the app you created in Automator, then click the Change All... button.
Windows
A similar but hopefully less-involved approach might work in Windows. You could probably create a batch file (.bat) with the following:
python C:\path\to\my\app\myapp.py %*
The %* expands to all arguments.
As long as you can associate a file extension with that batch file, then you could do that, and that's your solution. However, I haven't tried this Windows solution, so take it with a grain of salt. The Mac solution, on the other hand, I have tested.
By example, here's a universal solution I wrote for:
1) opening a Windows desktop link (*.URL) that's been copied to a Linux box.
Or
2) opening a Linux .Desktop link that's been copied to a Windows box.
Here's the Python script that handles both cases:
# UseDesktopLink.py
import sys
import webbrowser
script, filename = sys.argv
file_object = open(filename,'r')
for line in file_object:
if line[0:4]=="URL=":
url=line[4:]
webbrowser.open_new(url)
file_object.close()
On Windows, use Scott H's method (via a bat file) to handle the association.
On Linux, right-click a Windows URL file. Choose Properties, and Open With. Click Add to add a new application. Then at the bottom of the "Add Application" window, click "Use a custom command". Then browse to the UseDesktopLink.py file and click Open. But before you click Add, in the textbox below "Use a custom command", put "python " before the filename (without the quotes). Then click Add and Close.
Hope that helps.
Find any file of type foo
right-click -> Get Info or Click on the file icon,then click Get info or click on the file and hit Command+I
In the Open With pane that shows up, select the path to the python binary
Once selected, You can click the change All button
It'll ask for confirmation, just say continue
I found this old question while looking for an answer myself, and I thought I would share my solution. I used a simple c program to direct the arguments to a python script, allowing the python script to stay a script instead of needing to compile it to make things work. Here is my c program:
int main(int argc, char *argv[]){
char cmd[0xFF];
// For me, argv[1] is the location of the file that is being opened. I'm not sure if this is different on other OSes
snprintf(cmd,sizeof cmd,"python YOUR_PYTHON_SCRIPT_HERE.py -a %s", argv[1]);
system(cmd);
return 0;
}
I then compiled the c program and set that as the default application for the file extension.
Then, in the python script YOUR_PYTHON_SCRIPT_HERE.py, I receive the argument like this:
import sys
assert len(sys.argv) > 2 # Breaks if you call the script without the arguments
theFile = " ".join(sys.argv[2:]) # What the c program gives us
print(theFile) # Print it out to prove that it works
theFile will contain the location of the file that is being opened
Get the contents of the file by using:
with open(theFile,"r") as f:
fileContents = f.read()
On Windows:
Right click the file (I used a .docx file for this example)
Select Open with...
From the applications list, select python
Optional: Select the Always use the selected program to open this kind of file.
Note: this will run the contents of the .docx file in context of the python shell. It will immediately close once it is finished evaluating the contents of the file. If you'd like to edit the file in a word processor, perhaps you should download notepad++, and select that application as the default.

OS X: Determine Trash location for a given path

Simply moving the file to ~/.Trash/ will not work, as if the file os on an external drive, it will move the file to the main system drive..
Also, there are other conditions, like files on external drives get moved to /Volumes/.Trash/501/ (or whatever the current user's ID is)
Given a file or folder path, what is the correct way to determine the trash folder? I imagine the language is pretty irrelevant, but I intend to use Python
Based upon code from http://www.cocoadev.com/index.pl?MoveToTrash I have came up with the following:
def get_trash_path(input_file):
path, file = os.path.split(input_file)
if path.startswith("/Volumes/"):
# /Volumes/driveName/.Trashes/<uid>
s = path.split(os.path.sep)
# s[2] is drive name ([0] is empty, [1] is Volumes)
trash_path = os.path.join("/Volumes", s[2], ".Trashes", str(os.getuid()))
if not os.path.isdir(trash_path):
raise IOError("Volume appears to be a network drive (%s could not be found)" % (trash_path))
else:
trash_path = os.path.join(os.getenv("HOME"), ".Trash")
return trash_path
Fairly basic, and there's a few things that have to be done seperatly, particularly checking if the filename already exist in trash (to avoid overwriting) and the actual moving to trash, but it seems to cover most things (internal, external and network drives)
Update: I wanted to trash a file in a Python script, so I re-implemented Dave Dribin's solution in Python:
from AppKit import NSURL
from ScriptingBridge import SBApplication
def trashPath(path):
"""Trashes a path using the Finder, via OS X's Scripting Bridge.
"""
targetfile = NSURL.fileURLWithPath_(path)
finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder")
items = finder.items().objectAtLocation_(targetfile)
items.delete()
Usage is simple:
trashPath("/tmp/examplefile")
Alternatively, if you're on OS X 10.5, you could use Scripting Bridge to delete files via the Finder. I've done this in Ruby code here via RubyCocoa. The the gist of it is:
url = NSURL.fileURLWithPath(path)
finder = SBApplication.applicationWithBundleIdentifier("com.apple.Finder")
item = finder.items.objectAtLocation(url)
item.delete
You could easily do something similar with PyObjC.
A better way is NSWorkspaceRecycleOperation, which is one of the operations you can use with -[NSWorkspace performFileOperation:source:destination:files:tag:]. The constant's name is another artifact of Cocoa's NeXT heritage; its function is to move the item to the Trash.
Since it's part of Cocoa, it should be available to both Python and Ruby.
In Python, without using the scripting bridge, you can do this:
from AppKit import NSWorkspace, NSWorkspaceRecycleOperation
source = "path holding files"
files = ["file1", "file2"]
ws = NSWorkspace.sharedWorkspace()
ws.performFileOperation_source_destination_files_tag_(NSWorkspaceRecycleOperation, source, "", files, None)
The File Manager API has a pair of functions called FSMoveObjectToTrashAsync and FSPathMoveObjectToTrashSync.
Not sure if that is exposed to Python or not.
Another one in ruby:
Appscript.app('Finder').items[MacTypes::Alias.path(path)].delete
You will need rb-appscript gem, you can read about it here

Categories

Resources