I have this use-case that happens often in my django dev daily life : I want to execute a piece of code taken from my app into shell_plus
For example this queryset :
bookings_sent = Mail.objects.filter(_type=cts_mail.MailId.GIVE_MONEY).filter(
booking__in=bookings).values_list('booking', flat=True)
So I copy the line in shell_plus and press Enter but then the shell rightfully yells because of undefined cts_mail variable.
I have to find the import at the top of the file and paste it into the shell, then it yells for another constant, yadda yadda yadda...
Ideally, I'd like to select in ST3 the lines I want to execute in the shell and do a right-click "Prepend required imports" so the imports appear right on top of my selection and i can copy the whole block to shell_plus in one swoop.
Related
The problem:
I'm currently working on a programming language, which uses a simple python interpreter. The interpreter loops over every line with a bunch of if-statements.
The file extension I'd like to use is .ccp.
So far my progress. I want the computer to recognise .ccp files as a CalcScript file, and open it with the script.
I don't want to have a default filename which I can open using text = open("filename.idk","r").read(), I want to open a file like a 'normal' file. You double-click on the file in explorer, and it opens it in the python script. Regardless of the filename.
What I've tried:
Tinkering with the default applications in settings
Tinkering in regedit
Converting my .py file to .exe
Scouering the internet
My code:
https://github.com/AnonymousPixel/CalcScript
Sorry for bad English if there was any.
Summarizing my comments on the question, you can follow the steps below to achieve what you are asking:
Use sys.argv to access the command line arguments. For example the following script will just print all the arguments given to it:
import sys
print("Given arguments: ", str(sys.argv))
Let's name it myprogram.py.
You can then call it (I think) with: python myprogram.py arg1 arg2 arg3 and it will run and print the command line arguments.
Notice that the first argument (sys.argv[0]) is the script's path. So arg1 would be sys.argv[1], arg2 would be sys.argv[2] and so on.
I am saying to use sys.argv because as far as I remember double clicking a file with an extension which has a default opening program, will open that program with the file path as an argument.
Next step is to package your python script to an executable. This has been already asked and answered for example here (which is a duplicate, where you can follow the question which came before it to see even more examples). I used PyInstaller to test it (and on Windows OS). My command was like:
pyinstaller myprogram.py
... and it generated some folders and files. Specifically the folder dist\myprogram contained the executable along with its dependencies. You can then run your program by double clicking on it in the dist\myprogram folder. It should pop a CLI window, printing the arguments (ie only the program's path, since we called it without any other) and immediately exit. Or you can open a CLI window and run it with a command like:
myprogram argument1 argument2 argumentN
(supposing your current working directory is dist\myprogram) and it will indeed print the arguments.
Finally you have to set it up as the program which by default opens files with .ccp extension. On Windows 10, you can do this via:
Open up File Explorer.
Find a file with .ccp extension (or create one).
Right click on it.
Click on Properties on the dialog that pops up.
Go to General tab (if you are not already there) on the dialog that pops up.
On the Open with: section there is a button which reads Change. Click it.
Select More apps at the bottom of the dialog.
Make sure you have the Always use this app to open .ccp files checkbox selected.
Scroll to the bottom of the dialog and click on the blue text which prompts for manually selecting the default app, which in turn pops up a file chooser. I am not running on English language so it is a bit difficult to translate it exactly (I followed some online pages to actually see the default translation for the previous steps).
Select your executable as the default.
Confirm your choices by selecting Ok, Apply or anything else required.
Then you will also be able I think to change this extention later via:
Settings --> Apps --> Default Apps --> Choose default apps by file type.
Some references:
PyInstaller website and introductory manual.
Official page for step 3.
Unofficial page for step 3, a lot more detailed.
I want to do the following:
Save numeric data in a CSV-like formatting, with a ".foo" extension;
Associate the ".foo" file extension with some python script, which in turns opens the .foo file, reads its content, and plots something with a plotting library (matplotlib most probably).
The use-case would be: double-click the file, and its respective plot pops up right away.
I wonder how I should write a python script in order to do that.
Besides, the windows "open with" dialog only allows me to choose executables (*.exe). If I choose "fooOpener.py", it doesn't work.
This isn't really a programming question, but what you need to do is to figure out how to get the Python executable into the registry key that opens your data file.
For example, I created a little Python script called opener.py that looks like this:
import sys
print(sys.argv)
input()
Then I created a testfile.foo and used the "change" button in that file's property dialog to choose opener.py. (You can do this if you click Browse and change the Open With dialog's file filter to "All Files".)
Of course this didn't work (as you noticed). So I opened regedit and searched for opener.py and found it at the following registry key:
HKEY_CURRENT_USER\Software\Classes\Applications\opener.py\shell\open\command
The default value of this key was "C:\opener.py" %1. I changed it to python "C:\opener.py" %1. It worked!
Long story short, to do this properly you need to custom-edit the registry. Actually setting up the file association is more complex than just editing that one key (you have to also indicate that .foo is associated with opener.py).
An alternative approach would be to turn your Python script into a standalone executable using one of the several tools available for that purpose, or write a small executable in C that launches the script.
press the windows key
type cmd
right click the result and choose "run as administrator"
assoc .foo=foofile
ftype foofile="C:\Users\<user>\AppData\Local\Programs\Python\PYTHON~1\python.exe" "C:\<whatever>\fooOpener.py" "%1" %*
Use pythonw.exe if it's a .pyw file (to prevent a cmd window from spawning).
If you want to use an existing file type, you can find its alias by not assigning anything. For example, assoc .txt returns .txt=txtfile.
instead of editing registry, you can create batch file
opener.cmd
with content
python "C:\<whatever>\fooOpener.py" %1
and associate extension with this file.
It works!
I'm looking for a way to generate a ctrl+A (select all), and then ctrl+x in a python script. I know how to generate this in a specific app (pywinauto and other modules do that). But I'm looking for a way to send these keys in any apps (in any field of the active windows). I want to launch the python script containing these keys anywhere (the script will be launch using a key shortcut. Details below (1))
EDIT: I'm NOT trying to copy/past in the command windows (cf. the 2 last sentences). My script send the keys in the command windows, but that's the problem I'm trying to solve...
Using python pywinauto (or Ctypes or other modules)
I tried several propositions listed here with the same result.
I thought pywinauto could do it. Following pywinauto latest documentation I tried that:
open an (any) app containing a text field (that's the active windows)
place the cursor where you want to make the select all + cut/past
run the script bellow using an shortcut (so you won't leave the active windows)
from pywinauto.keyboard import SendKeys
SendKeys('^a^x')
Result
The code only print ^A^X in the python console. It doesn't do what it's suppose to do in the field of the active window (where I placed my cursor): it doesn't select all + cut the text.
Using autohotkey:
The only way I found to simulate a real crtl+A ctrl+C is by using autohotkey (it works but it's not a python solution):
save the code bellow in my AHK script: select_copy.ahk
Send, ^a
Send, ^x
create another AHK script called shortcut.ahk where you will specify a shortcut to launch select_copy.ahk (shortcut.ahk sould run constantly in windows background (2))
!^+G:: Run select_copy.ahk , C:\Users\Me\Desktop
(meaning: when I hit ctrl+alt+shift+G run the script select_copy.ahk)
result:
It works. when I call the ahk, it select/cut things in the active windows.
A combination of both did not work
I tried to launch the select_copy.ahk from within a python script (using subprocess.call) but I ended up with the same result than pywinauto (or Ctypes): it only prints ^A^X in the consol, but doesnt select&cut. So I'm wondering if python could really do what autohotkey does.
(1) What the script will do: I will launch the script (using a shortcut key) on one or another html editor, it will cut all the text, parse its source code, make some change put back the datas in the clipbboard, and past it. I'm only missing the first part (select all + cut) and the last part (past).
(2) It's not the big deal since shortcut.ahk contains also all my other ahk shortcuts and scripts.
Your AutoHotKey script should work, and does on my machine. However, I recommend that you just have one shortcut.ahk file containing the following:
!^+G::
Send, ^a
Send, ^x
Return
...and then put this in your python file:
subprocess.call("C:\\Path\\To\\AutoHotKey.exe /r C:\\Path\\To\\shortcut.ahk")
replacing the paths with wherever the AutoHotKey executable is, and wherever the shortcut.ahk file is.
Just as a side note: !^+G:: triggers on Alt+Shift+Ctrl+G, not Shift+Ctrl+G as you wrote in your question:
(meaning: when I hit ctrl+shift+G run the script select_copy.ahk)
EDIT: Also, from the phrase in the python console in your question it seems like you're trying to select all and then cut it in CMD. This will not work at all. Instead, if you want to simply clear the console, just use the command cls (Windows only; use clear in Linux). If you want to copy the entire console output and then clear it (i.e. cut) you're gonna need something different.
addressing Sublime Text 3 users here.
I wrote a couple of macros to enable spell-check and load a specific dictionary, as I constantly swap between French and English and I wanted a simple shortcut for this (instead of browsing the menu or two successive commands in the command pallet).
My macros work as expected (french-spellcheck.sublime-macro, english-spellcheck.sublime-macro).
But I would like to display a message in the Status Bar, for instance "Switched to French" or "Switched to English" (for some time, let say 5 sec).
I looked everywhere I know and I tried for some time, but apparently there is no way to do this in a command (that could be added at the end of the macro), as the set_status internal ST3's Python API command (from Window package) is only available for plugins...
Does any one has an idea of how to display a message to the SublimeText3 StatusBar in a command/macro and not with a plugin? Thanks!
There is no built in command that invokes the API methods for doing this (at least not a documented one), so there's no way to go about this without a plugin of some sort.
That said, in order to do what you want, the following is all you would need to save into a file named e.g. set_status.py in your Packages/User folder (alongside your macros). This provides a set_status command that takes a value named value for the text to display, as mentioned in the commented out portion of your macro file.
import sublime, sublime_plugin
class SetStatusCommand(sublime_plugin.TextCommand):
def run(self, edit, value="set_status: use arg 'value' to set text"):
self.view.window ().status_message (value)
This uses a different API than the one you mention in your macro file comments; status_message does the work of displaying a message in the status bar, waiting a few seconds, and then removing it, which makes the command simple to implement.
If you wanted more control (i.e. to change the duration) you would need to modify this to invoke the API commands your macro files already mention: view.set_status() and sublime.set_timeout().
I wonder if there is a program that I can use with a list of terms I want to replace instead of take one by one.
Example
À=À
â=â
Â=Â
å=å
Å=Å
ã=ã
Ã=Ã
Thank you in advance
I use UltraEdit and powergrep atm.
UltraEdit has 2 features for automating reformatting tasks: macros and scripts.
See UltraEdit forum topic When to use Scripts over Macros for a brief overview of the differences.
UltraEdit macro
An UltraEdit macro can be created by simply recording the replaces you manually do once on a file or you code them directly in Edit/Create Macro dialog.
A manual creation is done as follows:
Click in UltraEdit in menu Macro on menu item Edit Macro.
Click on button New macro.
Enter as macro name for example ReplaceEntities.
Uncheck macro property Show cancel dialog for this macro.
Let macro property Continue if search string not found checked.
Assign a hotkey or chord for quick execution by key if this is wanted for quick macro execution by key in future.
Click on button OK.
Back in Edit/Create Macro, there is now the new macro selected with 3 lines already present in edit field with the macro commands:
InsertMode
ColumnModeOff
HexOff
Below those 3 macro commands must be added for this reformatting task the macro code lines posted below.
Click on button Close and confirm the question to update the macro with button Yes.
The macro is then ready for usage
by assigned hotkey/chord,
by double clicking on it in Macro List opened via View - Views/Lists - Macro List in case of not being already visible (docked or floating), or
by using Macro - Play Any/Multiple Times.
Also Macro - Play Again can be very often used depending on which macro was last time executed.
The macro code required additionally to 3 standard commands already present in the dialog to replace in entire active file HTML entities is for example:
Top
UltraEditReOn
Find MatchCase "À"
Replace All "À"
Find MatchCase "â"
Replace All "â"
Find MatchCase "Â"
Replace All "Â"
Find MatchCase "å"
Replace All "å"
Find MatchCase "Å"
Replace All "Å"
Find MatchCase "ã"
Replace All "ã"
Find MatchCase "Ã"
Replace All "Ã"
It is necessary to save this UE macro (without or with other UE macros) into a macro file by using Macro - Save All.
For using this macro (and other macros store in same macro file) later again, it is necessary to load the macro file using Macro - Load.
With Macro - Set Auto Load it is possible to select a macro file for being automatically loaded on startup of UltraEdit so that the macros in this macro file are available from beginning without an explicit loading of the macro file.
The macro properties can be also changed later by using Macro - Delete Macro/Modify Properties. Don't forget to use Macro - Save All after making a change to a macro code or its properties to save this change in macro file, too.
UltraEdit script
UltraEdit scripts make use of the JavaScript core engine. An UltraEdit script is an ASCII/ANSI text file containing JavaScript core code with additional UltraEdit related scripting commands. This means an UltraEdit script can be written directly like any other text file and must not be edited in a dialog.
An UltraEdit script which makes exactly the same as the macro above would be:
if (UltraEdit.document.length > 0) // Is any file opened?
{
// Define environment for this script.
UltraEdit.insertMode();
UltraEdit.columnModeOff();
UltraEdit.activeDocument.hexOff();
// Move caret to top of the active file.
UltraEdit.activeDocument.top();
// Define all parameters for several Replace All in entire active file.
UltraEdit.ueReOn();
UltraEdit.activeDocument.findReplace.mode=0;
UltraEdit.activeDocument.findReplace.matchCase=true;
UltraEdit.activeDocument.findReplace.matchWord=false;
UltraEdit.activeDocument.findReplace.regExp=false;
UltraEdit.activeDocument.findReplace.searchDown=true;
UltraEdit.activeDocument.findReplace.preserveCase=false;
UltraEdit.activeDocument.findReplace.replaceAll=true;
UltraEdit.activeDocument.findReplace.replaceInAllOpen=false;
UltraEdit.activeDocument.findReplace.selectText=false;
// This property is only available since UE v14.10.
if (typeof(UltraEdit.activeDocument.findReplace.searchInColumn) == "boolean")
{
UltraEdit.activeDocument.findReplace.searchInColumn=false;
}
UltraEdit.activeDocument.findReplace.replace("À","À");
UltraEdit.activeDocument.findReplace.replace("â","â");
UltraEdit.activeDocument.findReplace.replace("Â","Â");
UltraEdit.activeDocument.findReplace.replace("å","å");
UltraEdit.activeDocument.findReplace.replace("Å","Å");
UltraEdit.activeDocument.findReplace.replace("ã","ã");
UltraEdit.activeDocument.findReplace.replace("Ã","Ã");
}
Such an UltraEdit script should be saved with file extension .js, for example ReplaceEntities.js.
Once an UE script is saved, it can added via Scripting - Scripts to the Script List with adding a short description for the script and assigning a hotkey/chord to the script for quick execution by key.
The script is then ready for usage
by assigned hotkey/chord,
by double clicking on it in Script List opened via View - Views/Lists - Script List or Scripting - Script List in case of not being already visible (docked or floating), or
by clicking on script file name in menu Scripting.
If an UE script is the active file AND it is written to run NOT on active document, the script can be also executed with Scripting - Run Active Script. But most scripts like the one above are written to run on active file and therefore requires adding the script file to the script list for execution.
The core objects and functions of JavaScript are not documented anywhere within UltraEdit although they can be also used in UltraEdit scripts. The documentation for the core features can be found on Mozilla Developer site.
The additional scripting commands of UltraEdit are documented in help of UE on page with title Scripting commands. There is additionally View - Views/Lists - Tag List containing the tag groups UE/UES Script Commands and also UE/UES Macro Commands for quick adding a scripting or macro command of UE in active file at current position of the caret.
Here is my umlaut2html-Makro which does a few automated text-replacements. I guess it can serve as inspiration ;-)
// Lessons learned from Mofi ;-)
UltraEdit.ueReOn();
UltraEdit.activeDocument.findReplace.mode=0;
UltraEdit.activeDocument.findReplace.matchCase=true;
UltraEdit.activeDocument.findReplace.matchWord=false;
UltraEdit.activeDocument.findReplace.regExp=false;
UltraEdit.activeDocument.findReplace.searchDown=true;
UltraEdit.activeDocument.findReplace.preserveCase=false;
UltraEdit.activeDocument.findReplace.replaceAll=true;
UltraEdit.activeDocument.findReplace.replaceInAllOpen=false;
UltraEdit.activeDocument.findReplace.selectText=false;
UltraEdit.activeDocument.findReplace.regExp=false;
UltraEdit.activeDocument.findReplace.replace("ä","ä");
UltraEdit.activeDocument.findReplace.replace("ö","ö");
UltraEdit.activeDocument.findReplace.replace("ü","ü");
UltraEdit.activeDocument.findReplace.replace("Ä","Ä");
UltraEdit.activeDocument.findReplace.replace("Ö","Ö");
UltraEdit.activeDocument.findReplace.replace("Ü","Ü");
UltraEdit.activeDocument.findReplace.replace("ß","ß");
Save this into a .js-file anywhere you like (MyDocuments\UE-Scripts might be a good choice), then call Script > "Scripts..." and "Add", navigate to select that .js-file.