What do the three arrow (">>>") signs mean? - python

I haven't been able to figure out what the >>> does, even though I often see it often in source code.

You won't see it in source code, it's probably documentation. It indicates an interactive session, and things typed into the 'interpreter' are marked with this. Output is shown without the arrows.
In fact, the python documentation often has a button >>>at the top right of example code to be able to hide the arrows (and output) so that you can copy and paste the code.
Shown:
Hidden:

'>>>' is the prompt of the interactive Python interpreter, meaning that the interpreter is ready to get Python statements typed in. It's occuring quite often in examples within the documentation of a Python program, in order to show which commands can be used and what will be the result of giving these commands to the interactive interpreter. For example, in a documentation of the print statement, one could give this example:
>>> print "Hello world."
Hello world.
This would be an actual snippet of a session with the interactive Python interpreter.
An interesting feature in IPython is that it ignores leading >>>, meaning that you can copy and paste code from such documentation without needing to remove the leading >>>:
In [1]: >>> print "Hello world."
Hello world.
(The prompt in IPython is In [n]:, where n is counting the interactive commands issued.)

Here are some of my findings on >>> and consequently ... complementing the previous answers.
You only see >>> when you are running Python in interactive mode prompting/asking the user for the "next command". Technical details here.
>>> and ... are not written in stone. These are stored in sys.ps1 and sys.ps2, and therefore can be changed. Further elaborated here.
>>> import sys
>>> sys.ps1 = "$ "
$
Every standard Python has this prompt unless you compile your own Python after changing >>> and ... to what you (sanely) wish to. Apart from that there seems to be a way to change it for all future interactive sessions by changing /usr/lib/python2.7/code.py but I couldn't find any success with it.

The >>> prompt is the Python interpreter’s way of asking you, “What do you want
me to do next?”, and it is called "chevron" prompt

In case you are trying to figure out how to exit a session, run this:
quit()

I found it to be called ' REPL'

Related

Why is IDLE's Shell color coding keywords in user response to input(prompt)?

I'm working on a Python 3 program that takes input from the user via the Python Shell. For some reason when I enter the information into the shell (once the input asks for info...), it's coloring keywords & functions with specific colors.
For example, if I type in "John is blue". It will color the word "is" as a keyword (Which it technically is but this is string input).
I haven't been able to bring up anything relevant on google so I'm bring the question here. Thanks.
Here is the code that runs the input.
if __name__ == '__main__':
global string
string = str(input('Enter info: '))
string = bytes(string.encode("utf-8"))
c = cont.key_gen_01()
c.func_01()
run_a = obf_01()
run_a.func_02()
#run_a.func_03()
run_a.func_04()
run_a.func_05(string)
Screen shot:
Colorizing in IDLE editor and Shell windows is done by the IDLE syntax colorizer. In Shell, it also colors console prompts ('>>> '), internal IDLE errors (now extremely rare), user code tracebacks, and user code output. (Colors can all be customized on the Highlights tab of the Settings dialog.) So the colorizer should not be turned off between code entries.
Unless your program is requesting entry of python code, I consider colorizing input() responses to be a minor bug. But it is not obvious how to tell the colorizer to ignore them. To a display, input() prompts are normal output. Besides which, responses can be entered before the prompt. Try the following with or without hitting ENTER before the prompt.
import time; time.sleep(5); s = input('what??? '); print(s)
The above also works in python, but at least in Windows Console, I don't see the entry until the prompt is displayed.
The Python input() function doesn't and can't do anything with how text you enter is displayed. It merely receives text after it has been typed and you hit enter. Instead, the color changes are applied by the IDLE shell window, which implements the input and output environment that the Python interpreter is connected to.
The IDLE Python shell treats all user input as Python source code when it comes to highlighting. This is just a change in how the text is rendered on your display, it has no influence on what string value is being returned from the input() function.
Other environments (IDE consoles, terminal windows, notebook UIs, etc) that can act as front-end displays for a Python interactive interpreter each can have their own specific ways of treating text.
You can print syntax highlighted text using python pygments
A good way to get started with is the prompt_toolkit moudle, comes with support for pygments and ALOT of command line features
Then you can create an prompt() which is input, and set the pygments lexer
check the prompt_toolkit docs or https://replit.com/#CodinUser/PyShell-15 to see a real life use of the syntax highlighting input pygments prompt_toolkit

IPython 5.0: Remove spaces between input lines

(This question is essentially this question, but for IPython version 5.0)
I'd like to have a classic prompt with IPython 5.0.
This question helps customize my prompt. In fact, I discovered that IPython has a class definition for the ClassicPrompts already.
All I need to do is to put the following in a file called 00-classic-prompts.py or some such in ~/.ipython/profile_default/startup/:
from IPython.terminal.prompts import ClassicPrompts
ip = get_ipython()
ip.prompts = ClassicPrompts(ip)
But different prompt lines still render as:
>>> print('Hello world!')
Hello world!
>>>
With an extra new-line before every input prompt. How can I remove this?
Please append this line on the bottom of your existing startup script:
ip.separate_in = ''
This is a documented feature but currently has no description, making it hard-to-find.

Python 3 print without parenthesis

The print used to be a statement in Python 2, but now it became a function that requires parenthesis in Python 3.
Is there anyway to suppress these parenthesis in Python 3? Maybe by re-defining the print function?
So, instead of
print ("Hello stack over flowers")
I could type:
print "Hello stack over flowers"
Although you need a pair of parentheses to print in Python 3, you no longer need a space after print, because it's a function. So that's only a single extra character.
If you still find typing a single pair of parentheses to be "unnecessarily time-consuming," you can do p = print and save a few characters that way. Because you can bind new references to functions but not to keywords, you can only do this print shortcut in Python 3.
Python 2:
>>> p = print
File "<stdin>", line 1
p = print
^
SyntaxError: invalid syntax
Python 3:
>>> p = print
>>> p('hello')
hello
It'll make your code less readable, but you'll save those few characters every time you print something.
Using print without parentheses in Python 3 code is not a good idea. Nor is creating aliases, etc. If that's a deal breaker, use Python 2.
However, print without parentheses might be useful in the interactive shell. It's not really a matter of reducing the number of characters, but rather avoiding the need to press Shift twice every time you want to print something while you're debugging. IPython lets you call functions without using parentheses if you start the line with a slash:
Python 3.6.6 (default, Jun 28 2018, 05:43:53)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: var = 'Hello world'
In [2]: /print var
Hello world
And if you turn on autocall, you won't even need to type the slash:
In [3]: %autocall
Automatic calling is: Smart
In [4]: print var
------> print(var)
Hello world
Use Autohotkey to make a macro. AHK is free and dead simple to install. www.autohotkey.com
You could assign the macro to, say, alt-p:
!p::send print(){Left}
That will make alt-p put out print() and move your cursor to inside the parens.
Or, even better, to directly solve your problem, you define an autoreplace and limit its scope to when the open file has the .py extension:
#IfWinActive .py ;;; scope limiter
:b*:print ::print(){Left} ;;; I forget what b* does. The rest should be clear
#IfWinActive ;;; remove the scope limitation
This is a guaranteed, painless, transparent solution.
No. That will always be a syntax error in Python 3. Consider using 2to3 to translate your code to Python 3
The AHK script is a great idea. Just for those interested I needed to change it a little bit to work for me:
SetTitleMatchMode,2 ;;; allows for a partial search
#IfWinActive, .py ;;; scope limiter to only python files
:b*:print ::print(){Left} ;;; I forget what b* does
#IfWinActive ;;; remove the scope limitation
I finally figured out the regex to change these all in old Python2 example scripts. Otherwise use 2to3.py.
Try it out on Regexr.com, doesn't work in NP++(?):
find: (?<=print)( ')(.*)(')
replace: ('$2')
for variables:
(?<=print)( )(.*)(\n)
('$2')\n
for label and variable:
(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n
You can use operator oveloading:
class Print:
def __lt__(self, thing):
print(thing)
p = Print()
p < 'hello' # -> hello
Or if you like use << like in c++ iostreams.
You can't, because the only way you could do it without parentheses is having it be a keyword, like in Python 2. You can't manually define a keyword, so no.
In Python 3, print is a function, whereas it used to be a statement in previous versions. As #holdenweb suggested, use 2to3 to translate your code.
I have configured vim to auto-add the parens around my debug def calls when I write the file. I use a simple watcher that auto-runs my updates when the timestamp changes. And I defined CTRL+p to delete them all. The only caveat is that I have to have them alone on a line, which I pretty much always do. I thought about trying to save and restore my previous search-highlight. And I did find a solution on Stack. But it looked a little too deep for now. Now I can finally get back to debugging Ruby-style with a quick p<space><obj>.
function! PyAddParensToDebugs()
execute "normal! mZ"
execute "%s/^\\(\\s*\\)\\(p\\|pe\\|pm\\|pp\\|e\\|ppe\\)\\( \\(.*\\)\\)\\{-}$/\\1\\2(\\4)/"
execute "normal! `Z"
endfunction
autocmd BufWrite *.py silent! call PyAddParensToDebugs()
map <c-p> :g/^\\s*\\(p\\\|pe\\\|pm\\\|pp\\\|e\\\|ppe\\)\\( \\\|\(\\)/d<cr>
I use these Python defs to do my debug printing.
def e():
exit()
def pp(obj):
pprint.PrettyPrinter(indent=4).pprint(obj)
def ppe(obj):
pprint.PrettyPrinter(indent=4).pprint(obj)
exit()
def p(obj):
print(repr(obj))
def pe(obj):
print(repr(obj))
exit()
def pm():
print("xxx")

Evaluation missing in SublimeREPL Python

I'm trying to get SublimeREPL to work with Python. However, whenever I send a Python command to the REPL with the keyboard shortcut, only output from stdout is displayed. The evaluation of the command should also be displayed, but isn't. Here is a succinct example, copy and pasted from the output in the REPL after sending the commands to the REPL from Python source via the keyboard shortcut.
>>> print 'This will print out'
This will print out
>>> 'But this will not'
>>> 1+1
I would have expected the following output (running manually from BASH terminal in Python produces this):
>>> print 'This will print out'
This will print out
>>> 'But this will not'
'But this will not'
>>> 1+1
2
One last note, manually typing commands directly into the Sublime Text REPL produces the desired output, but is much slower and inconvenient.
I'm running this using SublimeText3 with the default Python 2.7.5 interpreter on Ubuntu 13.10.
This is happening because the REPL is actually evaluating your code in the exact same manner that it would if you put all those commands in a file and ran it from the command line - it is not behaving as an interactive interpreter in this case.
If you want the REPL to behave more like IDLE, for example, you need to transfer your code to it, then switch over and run it from there, simply by adding Shift to your key sequence. So, if previously you were using Ctrl,, S to evaluate a selection, just use CtrlShift,, S instead to transfer your selection to the REPL. Switch tabs and hit Enter, and it should behave as you are expecting.

How can I add a command to the Python interactive shell?

I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:
def load(s):
# Do some stuff
return something
In order to call this function I have to type
>>> load('something')
I would rather be able to simply type:
>>> load something
I am running Python with readline support, so I know there exists some programmability there, but I don't know if this sort of thing is possible using it.
I attempted to get around this by using the InteractivConsole and creating an instance of it in my startup file, like so:
import code, re, traceback
class LoadingInteractiveConsole(code.InteractiveConsole):
def raw_input(self, prompt = ""):
s = raw_input(prompt)
match = re.match('^load\s+(.+)', s)
if match:
module = match.group(1)
try:
load(module)
print "Loaded " + module
except ImportError:
traceback.print_exc()
return ''
else:
return s
console = LoadingInteractiveConsole()
console.interact("")
This works with the caveat that I have to hit Ctrl-D twice to exit the python interpreter: once to get out of my custom console, once to get out of the real one.
Is there a way to do this without writing a custom C program and embedding the interpreter into it?
Edit
Out of channel, I had the suggestion of appending this to the end of my startup file:
import sys
sys.exit()
It works well enough, but I'm still interested in alternative solutions.
You could try ipython - which gives a python shell which does allow many things including automatic parentheses which gives you the function call as you requested.
I think you want the cmd module.
See a tutorial here:
http://wiki.python.org/moin/CmdModule
Hate to answer my own question, but there hasn't been an answer that works for all the versions of Python I use. Aside from the solution I posted in my question edit (which is what I'm now using), here's another:
Edit .bashrc to contain the following lines:
alias python3='python3 ~/py/shellreplace.py'
alias python='python ~/py/shellreplace.py'
alias python27='python27 ~/py/shellreplace.py'
Then simply move all of the LoadingInteractiveConsole code into the file ~/py/shellreplace.py Once the script finishes executing, python will cease executing, and the improved interactive session will be seamless.

Categories

Resources