I want to paste the output of my Python script into a spreadsheet. For this to work, the output should use hard tabs, and not spaces, to separate fields. How to I convince Python that tabs is what I want?
print("a\tb")
does not do it, and neither does
print("a", "b", sep="\t")
Your help is much appreciated!
Your suggestion of
print("a\tb")
will indeed output a<TAB>b.
Verify this yourself in Python Shell / IDLE, or by writing this a\tb string to file and opening it in any notepad-type program.
The problem likely arises in whatever you're using to view the output. In my current PuTTY setup, tabs are "invisibly" translated to spaces.
EDIT: For xterm, see this "bug" report.
Related
I am making a program involving ANSI escape codes, and they were all working fine on replit until I switched back to IDLE (3.9 on both). But it doesn't work:
it should have looked like this:
I have seen several posts before that complain that the IDLE doesn't support these escape sequences because it isn't a terminal, so I tried to do it directly from the cmd but the beastly symbol still appeared, this time as a boxed question mark:
I know that it won't work straight from the IDLE, so I wonder if you can import a software like mintty into python?
Powershell works though...
P.S. please don't tell me to import colorama or something! I really want this to be the way. I also don't have immediate access to iPython (even though I would like to) so it's not really an option for me... unless I have to :D
EDIT: the code I put across the python programs:
import sys, os
os.system("")
CSI = f"{chr(0x1B)}["
print(f"""{CSI}3m{CSI}1m{CSI}4m{CSI}31m
look at this""")
sys.stdout.flush()
# I put the sys.stdout.flush() and os.system("") to try and fix the problem...
The IDLE shell is not a terminal emulator and not intended to be production environment. The decision so far is that is should show program developers what their program's output, without interpretation. This may change in the future but no final decision yet.
If you are on Windows, I believe its console can be put into ANSI mode, but Python does not do that for you. I don't know if program code can do so.
As near as I can tell, there is not wrapper program that turns mintty into an importable python module. It would not make much sense. Rather, you would want to open mintty or a mintty-based terminal-emulator, such as git bash, and open python within that terminal instead of CommandPrompt.
ANSI code is a broad term. You have to specify which code page you are using. For example, my Windows is in Chinese Simplified. Therefore if I want to escape from UTF-8 default in Python, I would put # coding : cp936 on the first or second line of a script. Then it can read and write text files with the simplified Chinese coding.
Second Question:
Could I make a red/green/etc. font for every character and put it as print('...', file=...)? It should be possible because colored emojis exist.
It should work, but I would like to know how I could (if it's possible) automate this with some program that makes a file containing those characters and displays them with the previous print statement.
Cheers!
So, I'm trying to write a gzip file, actually from the net, but to simplify I wrote some very basic test.
import gzip
LINES = [b'I am a test line' for _ in range(100_000)]
f = gzip.open('./test.text.gz', 'wb')
for line in LINES:
f.write(line)
f.close()
It runs great, and I can see in Jupyter that it has created the test.txt.gz file in the directory listing. So I click on it expecting a whole host of garbage characters indicative of a binary file, like you would see in Notepad.
However, instead I get this ...
Error! test.text.gz is not UTF-8 encoded.
Saving disabled.
See console for more details
Which makes me think, oh my god, coding error, something is wrong with my encoding, my saving, can I save bytes ? Am I using the correct routines ?? And then spend 5 hours trying all combinations of code and modules.
The very simple answer to this is none of the above. This is a very misleading error message, especially when the code you've written was designed to save a binary file with a weird extension.
What this actually means is ...
I HAVE NO IDEA HOW TO DISPLAY THIS DATA ! - Yours Jupyter
So, go to your File Explorer, Finder navigate to the just saved file and open it. Voila !!
Everything worked exactly as planned, there is no error.
Hope this saves other people many hours of debugging, and please Jupyter, change your error message.
It is also possible to select the file and, instead of double-clicking to open, go to 'view' as it interprets it correctly (or well, mostly, depending on special characters, mine is in Spanish and apparently it doesn't support accents).
This way we can avoid looking for the directory where we got the file and not getting out of jupyter :)
In Python, is there a mean to enforce the use of spaces or tabs indentation with a per file basis ?
Well, perhaps "enforce" is too strong, more like a "recommendation".
I keep receiving patch files with mixed indentation and this is annoying... (to say the least) Python itself can tell when there is a problem, but I am searching something to do that at the editor level, like it exists for the charset.
Edit : Ok, my question wasn't clear, I am asking this because I keep receiving corrections and patches in any mix of tab/space you can imagine. I am using Mercurial as a DVCS, perhaps something exists at this level ?
Tim Peters has written a nifty script called reindent.py which converts .py files to use 4-space indents and no tabs. It is available here, but check your distribution first -- it may have come bundled in an Examples or Tools directory. (On the latest LTS Ubuntu, it is provided by the python2.7-examples package.)
If you can set up a Mercurial hook you should be able to run all files through reindent.py.
By the way, if you are using unix, then your system may also have the expand (and unexpand) command, which convert all tabs to spaces (and spaces to tabs). However, in this case, I think reindent.py is the right tool.
Look at the tabnanny module: — Detection of ambiguous indentation.
This is something your editor should do for you. Most editors (try Notepad++ for example, it's free) will let you set whether hitting tab enters a tab character or a number of spaces. I'd recommend using two spaces instead of tab in all files (I find 4 is too much). Using spaces instead of tabs is better as it means that you can indent stuff using both the space & tab keys without worrying about messing up your files.
If you have files that have a mix it isn't hard to write your own script to convert tabs to spaces
As explicited in PEP 8, never mix tabs and space. However, a file with both may just run...
As it says there:
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively.
When invoking the Python command line interpreter with the -t option, it issues
warnings about code that illegally mixes tabs and spaces. When using -tt
these warnings become errors. These options are highly recommended!
the solution is therefore to use as a default:
python -t my_mixed_code.py
To answer at the editor level, this depends on the editor, please specify!
Does anyone know of an already-written Python script, tool, or editor that will check for unbalanced multi-line tokens? (parentheses, quotes, {}, [], etc.)
I've been writing Python code in IDLE, and every so often I'll get "EOF token in multi-line statement" and start swearing, because it means that somewhere in about 200 lines of code I forgot a closing parenthesis or quote and IDLE can't tell me where. This seems like a fairly straightforward thing, I just don't really have the time or headspace to work it out myself right now.
Much thanks
I use Eclipse with PyDev. It's very good for this sort of thing, and lots more.
emacs will automatically highlight matching pairs of parentheses/brackets/quotes/etc. as you type them, and it will inform you immediately if you mismatch them (e.g. if you type a [ followed by a )). I'm sure vim also does this, but since I don't use vim, I can't say with certainty.
PyDev is the best IDE to develop in Python. Has this feature and a lot of more.
If you use the vim text editor, there is a syntax highlighter for Python that might be of some help. Vim's python indenting rules also line up a new line with an unmatched open parenthesis from the previous line. That's been my visual cue that something is unbalanced.
When I am working with a Python Interpreter, I always find it a pain to try and copy code from it because it inserts all of these >>> and ...
Is there a Python interpreter that will let me copy code, without having to deal with this? Or alternatively, is there a way to clean the output.
Additionally, sometimes I would like to paste code in, but the code is indented. Is there any console that can automatically indent it instead of throwing an error?
Related
Why can I not paste the output of Pythons REPL without manual-editing?
IPython lets you show, save and edit your command history, for example to show the first three commands of your session without line numbers you'd type %hist -n 1 4.
WingIDE from Wingware will let you evaluate any chunk of code in a separate interpreter window.
IPython will let you paste Python code with leading indents without giving you an IndentationError. You can also change your prompts to remove >>> and ... if you wish.
I have a vim macro to "paste while cleaning interpreter prompts and sample output [[==stuff NOT preceded by prompts" and I'll be happy to share it if vim is what you're using. Any editor or IDE worth that name will of course be similarly easy to program for such purposes!
Decent text editors such as Notepad++ can make global search and replace operations that can replace >>> with nothing.