Python highlighting in emacs - python

I am using emacs 23 -nw and xterm installed on Debian Squeeze. I need highlighting with python but I don't have it. How can I enable it?
Edit:
Thanks for all answers, the problem is that
I have googled a lot, really.
I have the code on a file with extension .py
The script starts with #!/usr/bin/python, as one of the the answers points I have changed to !#/usr/bin/env python
I used M-x and tried to find something related to python, well there many options which do not solve my problem.
Sorry my question was not very precise and I even accept -10 but I don't have highlight which would give me red highlight for lines starting # etc. To be more precise I have a very a dull highlight; lines with # are white, lines between """ """ are green, some of the variable names are yellow but don't know why not all. [import, as, from] are light blue, [open, max, and other function names] are dark blue etc. And besides my 200 lines of code is working.

I'm not sure if this is right, but try the following.
1) M-x
2) type in "python-mode". Tab completion works here so type in "pyth" and hit tab and you can see what your options are.
mj

If you run Emacs from xterm with emacs -nw, you'll have a different color layout than if you run the same color mode in an X window. Differences include big changes in the highlighting of comments, different colors assigned to various keywords and (rarely in my experience, though Python comments seem to fall into this category) failure to highlight some elements.
I'm not really sure why this happens, but it doesn't seem to be a problem on your end since it's consistent on every machine I've worked on. If it really bugs you, and you really, really want to keep running from xterm, take a look at the color-theme module, it may help.

Emacs 23 should know about Python out of the box. Does the name of your Python file end with .py, or does the file have #!/usr/bin/env python as the first line? If you're creating a new file, make sure the filename ends with .py. You can also use M-x python-mode as mentioned in another answer. If none of that works, check that your terminal actually supports color.

Related

Is it possible to make pycharm's run display section display the same as actually running the program would?

Disclaimer: Sorry if the question is stupid or repeated, I've tried to find similar ones that answer what I need to know but I couldn't. I've started to learn programming about 1 month ago and this is my second time on this website. Feel free to point out any errors or better ways to formulate my questions on stackoverflow, I'll be grateful.
Context:
I was trying to find out a way to print a string - in this case ' º ' - after my user's input - an angle -, on the same line.
I need an alternative way to do this, or help with the one I'm using.
What I got from my research is that, apparently, using the command os.system(cls) should erase the previous line, and putting \033[A before the string should move the cursor up one line. So using these two together should erase the previous line and then overwrite it.
Here's my try:
from os import system
cls = lambda: system('cls')
angle = float(input(f'Insert an angle:'))
cls()
print(f'\033[AInsert an angle:{angle}º')
Desired result on run:
Insert an angle: *60*º # being 60 the user's input
Actual result on pycharm:
Insert an angle:60
Insert an angle:60.0º # for some reason, you can't see it when paste it here, but there's a symbol of a crossed rectangle on the beginning of this line on Pycharm's run
How it looks on pycharm's run terminal
As you can see, the line isn't getting overwritten, only repeated.
What is weird is that when I run this program with Python 3.8 instead of Pycharm, it works as intended, but, on Pycharm, the line isn't overwritten. Instead, Pycharm just prints a crossed rectangle symbol.
Why does it work when executing the file with Python 3.8, but not when pressing "run" on pycharm?
Is there a way to avoid it?
Are there better alternatives to printing a string on the same line as an input?
In cases where I need special printing (ANSII escape codes, backspacing...), I use the actual Terminal, not the Python Console.
For whatever reason, interactive consoles, regardless of IDE, seem to have issues with handing specialties like that. With the normal Terminal, it works as expected:
I have never found a way of having the interactive console handle cases like this.

Are there any risks/downsides to putting emojis in code?

I sometimes use emojis in programs to highlight certain parts of the code (in open source libraries). I rarely use more than say 5-6 per script and I find they really stand out due to their colors in a text editor.
Typically, they are transient markers and will be removed when whatever issue they are associated with is closed.
My question is: are emojis liable to cause any issues in the general Python toolchain? This includes, but is not limited to: git, github, pypi, editors, linters, interpreter, CI/CD pipelines, command line usage...
I haven't seen any, but then again I rarely see emojis in code. This is a Python 3 only question, so Python 2 unicode aspects are out.
(This question is not about whether this looks professional or not. That's a valid, but entirely separate consideration.)
Some examples:
# ⚙️ this is where you configure foo
foo.max_cntr = 10
foo.tolerate_duplicates = False
# 🧟‍♂️🧟‍♂️🧟‍♂️ to indicate code to be removed
some dead code
# 👇 very important, don't forget to do this!
bar.deactivate_before_call()
In terms of risks, there aren't really any real ones. If you use them in comments they'll be removed/ignored at runtime anyway so performance-wise there's no issues.
The main issue that you could run into is that some Linux distributions (distros) DONT support emojis, so they'd fallback to some standard unicode character (generically a white rectangle with a cross through the middle), so this could make comments hard to understand.
But in personal use: no not really, there's no issues.
TLDR: Probably not, but maybe.

Disable on-the-fly PEP8 checks, only check when saving file

I'm using PyCharm Community Edition 4.5.4, and I hate how it notifies me of every little "mistake" I make even when I have full intention of fixing it within 30 seconds.
My style is to kind of write everything at once (instead of finishing one thing before moving to the other), and thus every second word in my code gets highlighted as variable 'x' is not used or Unresolved reference 'x' because I already moved to an other section of my code, intenting to finish the for loop later. If I do something like:
for x in my_list:
pass
And then move to define my_list on top of the file, it will instantly highlight Local variable 'x' is not used. I wish to write my whole code freely, and then after hitting save, I wanna know what mistakes I made.
Is there any way to disable the PEP8 checker, so it would only check when I actually save the file, instead of when I type anything at all?
I have had problems with this issue too.
Unfortunately, there seems to be no documented way of doing what you're requesting. The PyCharm Articles on Code Inspection and Configuring Inspections really don't hint at any such possibility.
Additionally the config file in ~/.PyCharm40/config/inspection/Default.xml isn't what you would call rich in options (note: I have no idea if more options exist, couldn't really find appropriate documentation).
Since pep8.py is apparently ran continuously as a background process in PyCharm, I also checked whether a configuration of these processes was possible. Unfortunately (again), no useful results were found.
To make things worse, there seems to be no relevant plugin available in their plugin repository to allow for further tweaking of the inspection tool.
The other option I tried was by changing the settings in PyCharm and resort to manual calls to pep8. I unselected the inspections for pep8 from Settings | Editor | Inspections | Python tab and then ran the manual inspection by pressing Ctrl + Alt + Shift + I and entering the two pep options. It does not seem to catch the same coding convention errors.
You probably have two options now, one is switching to another IDE as Adam Smith suggested (or noted, actually) and second is trying to maybe get some help on the PyCharm forum.

Difference in solarized gvim theme

I am using a Solarized theme for (g)vim, and having an issue with small difference between the screenshot on the site and what I am actually having.
The screenshot for python on the theme's site is here:
(source: ethanschoonover.com)
, and mine is
They have a small difference (that I can see) in import statement (color is different). It sort of drives me crazy. Is my case correct, and that's what supposed to happen, or my settings are wrong?
I've installed the theme using vim-addon-manager plugin system.
Thanks.
The first thing you can check is what :highlight groupings are being applied to your import statement, I have a key mapping for a function which can do this:
" Show the stack of syntax hilighting classes affecting whatever is under the
" cursor.
function! SynStack()
echo join(map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")'), " > ")
endfunc
nnoremap <F8> :call SynStack()<CR>
If you :source a file containing this or put this in your .vimrc and reopen vim, we can now check what highlighting is being applied to import.
When I press F8 on an import I receive the message pythonInclude, now if you don't see that there may be something wrong with the parsing of python file and the keyword import hasn't been picked up on. We can then look at what rules are being applied to that-
:highlight pythonInclude
This gives me-
pythonInclude xxx links to Include
If we follow this then we can see what rules are being applied to Include group. This will probably go deeper, Include xxx links to PreProc. If you get this far your highlighting groups are probably correct. If you didn't link to PreProc there maybe another plugin overwriting the highlight group, or a similar issue. You can then check what colors the PreProc is setting. You can override a highlight group link, :highlight link pythonInclude Function this will now display imports as the same color as Functions!
You can also modify the colors and formatting applied to different highlight groupings however I will leave you to discover those on your own. Much more help can be found in :h :highlight, but I hope this helps start your debugging process!

Can I get Python debugger pdb to output with Color?

I'm using PDB a lot and it seems it would be even better if I could add systax highlighting in color.
Ideally, I'd like to have to the path to the code a lighter color.
The line of actual code would be syntax highlighted.
I'm using OS X and the Terminal app.
Python 2.7
pdb doesn't support colorization. However, it's not that hard to get it, even if you're a command-line addict (as I am;-) -- you don't have to switch to GUIs/IDEs just to get colorization while debugging Python. In particular, command-line tools usually work much better when you're accessing a remote machine via SSH, saving a lot of the bandwidth and latency issues that any remote access to GUIs and IDEs can inflict on you;-).
Specifically, for the task you're asking about, consider ipdb (you also need ipython, which offers a far more advanced shell than plain interactive Python, on which ipdb relies). Both offer you good tab completion, enhanced tracebacks, and colorization -- ipython for your normal interactive work, ipdb with the same features when you're debugging (otherwise just about the same as pdb).
You could try pudb, which works in the terminal and looks like this:
I haven't tried some of the options mentioned in other answers, but to judge from the PyPI pages, pudb is better maintained and better documented.
Take a look at pdb++ - it is a drop-in replacement for pdb that fills all your requirements and adds some other nice features such as tab completion and new commands such as watch and sticky.
Here is a sample config file that will enable colours (add this after creating the file: touch ~/.pdbrc.py):
import pdb
class Config(pdb.DefaultConfig):
use_pygments = True
pygments_formatter_class = "pygments.formatters.TerminalTrueColorFormatter"
pygments_formatter_kwargs = {"style": "monokai"}
This might not possible for you, but have you tried using a graphical debugger (like the one in eclipse/pydev)? It will give you your syntax highlighting and much more.
I only use pdb directly if I don't have an option, because a graphical interface is just that much nicer.
In case someone hit the problem with colorization in a console.
My console had white background while ipdb was also adding rather light colors to syntax (for example variables were white). Pressing man ipython shows that we have 3 colors available: 'nocolor', 'linux', 'LightBG'. Ipdb was in my case installed via easy_install into my virtualenv. So it was trivial to look into ipdb source and modify it (hint search for ipdb/init.py in your env). Then I've modified following:
def set_trace():
ip = ipapi.get()
+ def_colors = ip.options.colors
+ def_colors = 'LightBG'
Pdb(def_colors).set_trace(sys._getframe().f_back)
It's a kinda hackish solution but well its for debugging purpose on my working station so its sufficient. But if anyone finds something better. Please send me a message on what to do.

Categories

Resources