Are there any keyboard shortcuts for formatting in Python? - python

After we write a code in Matlab we can use ctrl+A+ctrl+I and ctrl+A+ctrl+J to format our code (comments, loops alignment etc). Is there something similar or any helpful keyboard shortcuts in Python?
Also, just like we can use upward arrow to copy our previous command window history in Matlab, is it possible or some keyboard shortcut to do that in Python?
Thanks!

Python is a programming language, not an integrated development environment (IDE), therefore it has no "keyboard shortcuts" or the like. Each given development environment may offer different facilities or the like. You appear to consider GNU Readline (typically used in the simple text-mode interpreter environment that many Python executables bundle) as "part of Python" -- but that's a misconception; readline is a perfectly general library for interactive input in command-line environments, and Python only one of the many programs using it. Another environment usually bundled with Python is IDLE, a GUI one, and of course the editing facilities are completely and drastically different. There are many third-party environments such as "Wing IDE" and each offers a drastically different set of editing features and facilities from all the others.
To summarize: your question makes no more sense about Python per se than it would about (say) C, or Java, or any other programming languages. Don't let (usually proprietary) programming languages that come with bundled IDEs confuse you on this subject!

If you use the Python IDLE (comes with Python on Windows, readily available on Linux and Unix flavors), most of the formatting work is done for you. For instance, IDLE automatically indents loops and any other code block after a :. This is far better than writing Python scripts in a standard text editor like gedit, emacs, vim, or Notepad, especially since you can simply press F5 to run the script.
As for previous commands, the biggest disadvantage to the Python shell is that you cannot press the up arrow to get the last command. However, if you use the non-GUI shell (in the Windows command prompt or a Unix terminal, the command is python), you can use the shell's command recall to get the last command.

If you use emacs, then
you can press tab anywhere on a line and it will properly indent that line relative to the preceding line (making the assumption that the current block is continuing).
you can mark selections of text and press C-c < and C-c > to move blocks of text left and right.
These are the two that I actually use with any regularity. I'm sure that anything that any other editor can do, emacs can do too ;)
on the whole, formatting python code is difficult for a program to do because the indentation drastically affects semantics.
consider
for i, item in enumerate(lst):
if i % 2:
sum += i * int(item)
return sum
and
for i, item in enumerate(lst):
if i % 2:
sum += i * int(item)
return sum
Do you really want your editor deciding which one you mean?

Related

Difference between print and click.echo in Python 3?

I am creating CLI app for Unix terminal using click module. So I see two ways how I can display data:
print(data) and click.echo(data)
What is difference between them and what should I use?
Please, read at least quickstart of library before using it. The answer is in the third part of quickstart.
If you use click click.echo() is preferred because:
Click attempts to support both Python 2 and Python 3 the same way and to be very robust even when the environment is misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken.
What this means is that the echo() function applies some error correction in case the terminal is misconfigured instead of dying with an UnicodeError.
As an added benefit, starting with Click 2.0, the echo function also has good support for ANSI colors. It will automatically strip ANSI codes if the output stream is a file and if colorama is supported, ANSI colors will also work on Windows. See ANSI Colors for more information.
If you don’t need this, you can also use the print() construct / function.

Enable python autocompletion in Vim without any install

I am coding Python3 in Vim and would like to enable autocompletion.
I must use different computers without internet access. Every computer is running Linux with Vim preinstalled.
I dont want to have something to install, I just want the simplest way to enable python3 completion (even if it is not the best completion), just something easy to enable from scratch on a new Linux computer.
Many thanks
Unfortunately Vim, by default doesn't do what you want, you are pretty much limited to the Ctrl-P style, which is better than it seems once you get used to it.
However i also often find myself working on machines that are not allowed to access the internet or have other files placed on them and When i find myself in this situation and i am using an unfamiliar language i sometimes use Vim's dictionary completion: http://vim.wikia.com/wiki/VimTip91
To populate this dictionary i cat / trim / filter the man pages for the language to get a variety of keywords. I ram these into a filetype specific dictionary: au FileType * execute 'setlocal dict+=~/.vim/words/'.&filetype.'.txt'
Obviously this isn't the greatest solution and it is a bit heavy handed but it does provide a certain degree of "What is that function called" type stuff.
If you have compiled vim with +python3, you can try omnifunc.
Add following to your ~/.vimrc:
au FileType python setl ofu=python3complete#Complete
Then in insert mode, just type CtrlX + CtrlO.
See :help omnifunc.
by default, Ctrl-P in insert mode do an autocompletion with all the words already present in the file you're editing

Python IDLE/Terminal return back after error

When reading a book or just coding on terminal/IDLE it's common to make typo, forgot brace or comma etc. After I got error and all what I wrote before is lost.
Then I have to write down code again..
Is there any way/option to return back all what write before and just edit mistake and continue to code?
In Idle (at least my version, Python 2.7.10 on windows), you can simply copy paste your code. In the python interpreter, you can't afaik, however you can use the up/down arrow keys to recall lines you previously "submitted" (i.e. typed and pressed enter).
If I understood correctly, IDLE is a GUI (graphical user interface - a visual representation of a program rather just through text) made to have a bit more features for programming in Python. You can use IDLE interactively, like in Terminal (a.k.a command line), or use it to write your script rather than in a separate text editor. Then once you save your script/program you can do neat things like run it directly from IDLE. There's nothing more special about the Terminal, you just have to do some more work.
Furthermore, all the code you have written on your GUI is on the cache memory which is used in system to store information recently accessed by a processor. So, I suggest you write again your code you can't recover them without saving.
To avoid these kind of problems use Git!
Git is a version control system that is used for software development and other version control tasks.
IDLE's Shell window is statement rather that line oriented. One can edit any line of a statement before submitting it for execution. After executing, one may recall any statement by either a) placing the cursor anywhere on the statement and hitting Enter, or b) using the history-next and history-prev actions. On Windows, these are bound, by default, to Alt-p and Alt-p. To check on your installation, Select Options => IDLE preferences on the menu. In the dialog, select the Keys tab. Under Custom Key Bindings, find the 'histor-xyz' actions in the alphabetical list.
For short, one-off scripts, I have a scratch file called tem.py. Since I use it often, it is usually accessible via File => Recent files.

IPython 5.0 and key bindings in console

The new release of IPython does not depend any more on readline but uses the pure Python library prompt-toolkit, solving maintenance problems on Apple's and Windows' systems.
A new feature is the ability to edit a multi-line code block, using the cursor keys to move freely in the code block — with this power it comes, at least for me, a problem: because a ret inserts a new line in your code, to pass the whole block to the interpreter you have to use the shortcut alt+ret or possibly the less convenient key sequence esc followed by ret.
I say, this is a problem, because my terminal emulator of choice is the XTerm and, on many Linux distributions, the shortcut alt+ret is not passed to the application but it is directly used by the XTerm in which IPython is running, to toggle the screen-fullness of the said terminal (#ThomasDickey, xterm's mantainer and co-author pointed out that, by default, xterm doesn't care to send to the application the modifier bit on Enter even when one unbinds the Fullscreen action).
For this reason I'd like to modify at least this specific IPython key binding.
I've found instructions (sort of) for the previouos versions, the readline based ones, of IPython that do not apply to the new, 5.0 version.
What I would need are instructions that lead me to find, in IPython's user documentation, the names of the possible actions that I can bind, the names of the shortcuts to bind with the actions and the procedure to follow to configure a new key binding.
Failing to have this type of canonical answer, I may be happy with a recipe to accomplish this specific keybinding, with the condition that the recipe still works in IPython 6.0
You could change xterm's configuration.
xterm is configurable (and documented). In the xterm manual, the Default Key Bindings section shows the default binding for this key:
Alt <Key>Return:fullscreen() \n\
You can suppress that binding in more than one way:
using the omitTranslation resource to suppress the feature
setting the fullscreen resource to never
However, just suppressing it will not make it send something interesting (xterm ignores the modifier for Enter). Setting a translation resource works, e.g., in your $HOME/.Xdefaults file:
*VT100*translations: #override \n\
Alt <Key>Return: string("\033[27;3;13~")
The ctrl+j or ctrl+m keyboard shortcuts are validating the entry.
Modifying keyboard shortcuts in configuration when using prompt_toolkit is not (yet) possible; though it is pretty easy if you install IPython from source. If you look at the file IPython/terminal/shortcuts.py you will see that it contains the various logic; in particular you will find:
# Ctrl+J == Enter, seemingly
registry.add_binding(Keys.ControlJ,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
))(newline_or_execute_outer(shell))
This bind CtrlJ (enter) to the function newline_or_execute_outer which is responsible for adding new lines; it's define later in the file. In particular if you press enter twice at the end of a block of code, it should execute the block without the need to use any other shortcuts.
Strip the logic that adds new lines:
def execute_outer(shell):
def execute(event):
"""When the user presses return, insert a newline or execute the code."""
b = event.current_buffer
# some logic to also dismiss the completer
b.accept_action.validate_and_handle(event.cli, b)
return execute
Bind it around line 20-something:
registry.add_binding(Keys.ControlE,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
))(execute_outer(shell))
And enjoy. If you are unhappy with the documentation we welcome help; For example, taking the gist of the answers there and contributing them back. It is a bit hurtful to read harsh comments when we do say in release notes:
New terminal interface
The overhaul of the terminal interface will probably cause a range of minor
issues for existing users. This is inevitable for such a significant
change, and we’ve done our best to minimise these issues. Some changes that
we’re aware of, with suggestions on how to handle them:
IPython no longer uses readline configuration (~/.inputrc). We hope that
the functionality you want (e.g. vi input mode) will be available by
configuring IPython directly (see Terminal IPython options). If something’s
missing, please file an issue.
...
Helping actually improving IPython to have configurable keybinding with actions name is also appreciated, so then you will be able to answer your own question.

Linux: write to stdin of python interpreter process and have that process evaluate input as code

I am running gnu linux (Linux Mint to be specific). The following is my desired workflow:
I open vim in (say) process 1000 and then start up a python interpreter in process 1001.
I write some code in vim and then select certain lines and then write those lines to the file /proc/1001/fd/0.
At this point I would like the python interpreter to interpret this as code and execute it as if it were typed in directly.
This does not work as desired. Instead the text is displayed on the interpreter's screen, but it is not executed (similar to when error messages of subprocesses are displayed in bash). I presume this has something to do with the fact that my workflow isn't playing well with readline (or some sort of equivalent library). Or my problem might just be that the python interpreter was never designed to be used this way (for presumably security and other reasons).
I understand there are many IDEs with similar functionality, but I was hoping that something simple might work. I'm curious if it's something that can be fixed or if there is something fundamental that I'm misunderstanding.
It exists and it's called vim-slime
The only requirement is that you run the Python interpreter inside tmux or screen, or even better: byobu
Installing the vim-slime plugin is easy if you're using vim-pathogen:
cd ~/.vim/bundle
git clone git://github.com/jpalardy/vim-slime.git
See the vim-slime page for configuration details, but if you're using tmux, simply add the following to your .vimrc and re-start Vim:
let g:slime_target = "tmux"
Trying it out
Type in some Python code inside Vim:
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
Then press Ctrl-c-Ctrl-c to tell vim-slime to send the contents of your current buffer to another window. The first time you run it, vim-slime will ask you which screen/tmux window to send it to, but after that, press the key-sequence and it will send it wherever you told it to the first time.
vim-slime is visual-mode aware, too! If you only want to send a few lines to Python, enter visual-line mode with V, highlight the lines you want, and press the same Ctrl-c-Ctrl-c key sequence to send just those line.

Categories

Resources