ANSI Escape Sequences Fail in Cygwin - python

I am trying to create a 'drop down menu' for a CLI program using ANSI escape sequences in Python 2.7.2. I use ANSI escape sequences to change the 'options' to red and display them below the input line, then afterwards clear them.
I am able to run the code on a system running Ubuntu 10.04LTS which runs Python 2.6.5, but am not able to get the program to run on a Windows XP machine running Cygwin minTTY 1.0.3. Is there an issue with sys.stdout.flush() in Windows or Cygwin? Is it a Python 2.6 to 2.7 issue? Don't really know where to start the debug.
#!C:\Python27\python.exe
#!/usr/bin/python
import sys
table = {1:'foo', 2:'bar', 3:'foo'}
print '\n'
for item in table.keys() :
sys.stdout.write('\033[1;31m %s) %s\033[0m\n' % (item,table[item]))
sys.stdout.flush()
sys.stdout.write('%s' %((item+1)*'\033M'))
sys.stdout.flush()
answer = raw_input("Select foobar: ")
sys.stdout.write('\033[J')
sys.stdout.flush()
print 'You have selected %s' % (table[answer])
The problem is that the raw input text does not print out until after you make your selection in minTTY (again, code works fine on Ubuntu), which kind of defeats the purpose of prompt text. Thanks in advance - Paul

You are not able to do this because Windows console does not support ANSI at all.
Back in MSDOS days there was an ANSI.SYS driver that you could load in order to enable them but not anymore.
My impression is that you will need to investigate the use of something like https://pypi.python.org/pypi/UniCurses if you want to build a TUI interface (text-user-interface)
References:
How to make win32 console recognize ANSI/VT100 escape sequences?

Related

C# args[] parameter about path with space on python code

I made some c# program and I tried to use c# program on Python.
C# program is CLI and use by CMD.
On CMD prompt I can use my program like below command
test.exe "C:\Users\Downloads\test file\1.txt" "C:\Users\Downloads\test file\2.txt"
But when I tried on python code.
AUDIO_TOOL = r"C:/Users/Downloads/test.exe"
filepath = r"C:/Users/Downloads/test file/1.txt"
binary_file_path = r"C:/Users/Downloads/test file/2.txt"
subprocess.call(["%s" % AUDIO_TOOL, r"%s" % filepath, r"%s" % binary_file_path], shell=True)
path that without space work properly but path with space does not work at all.
please help me.
You have to enclose the whole command in quotation marks
this How do I use spaces in the Command Prompt? may be help you

How to run a url from inside a python script to command line?

I have this command line text that I want to run inside my python script to the command line. Any suggestions on how to do this?
explorer "ms-drive-to:?
destination.latitude=47.680504&destination.longitude=-122.328262&destination.name=Green Lake"
If you want to effectively run this in python shell,like this: # it will open windows map
>>> !explorer "ms-drive-to:?
destination.latitude=47.680504&destination.longitude=-122.328262&destination.name=Green Lake"
If you want to run in code, do like others method.All the answers are correct.
import os
command_str = 'explorer "ms-drive-to:? destination.latitude=47.680504&destination.longitude=-122.328262&destination.name=Green Lake"'
os.system(command_str)
# it will open windows map, and driving directions to Green Lake from your current location.
Be careful to use double quotes, single quotes will not be recognized correctly!
windows uwp info: https://learn.microsoft.com/en-us/windows/uwp/launch-resume/launch-maps-app
Sure, you can do something like is described in this post:
https://raspberrypi.stackexchange.com/questions/17017/how-do-i-run-a-command-line-command-in-a-python-script
Seems like you should use subprocess:
Running Bash commands in Python

Python 3.6 on linux: Problem with flushing what i want to write to the stdout

I'm pretty new to python and linux and I'm running into a problem...
So I'm trying to run the following code
(It is supposed to inform the person in front of the terminal, that the program is still running and then delete that line after 1 second):
import sys
while True:
# do something
sys.stdout.write("Still going...")
time.sleep(1)
sys.stdout.write("\r")
sys.stdout.flush()
This works perfectly fine on windows on python 3.8, but when i run it on my linux vps with python 3.6.9 via the "python3" command it doesn't flush the "\r", so the "Still going..." line only gets deleted and immediately reprinted the next time it reaches sys.stdout.write("Still going...").
If anyone has an idea what's going on here - please tell me
Any help is appreciated!
Windows, Mac OS and UNIXes code new lines with differents chars.
Windows uses \r\n
Mac OS uses \r
UNIXes use \n
if you want your program to be cross-platform, you should use os.linesep instead of an OS-specific linebreak
answering the comment:
Indeed on Windows, \r just return at the start of the line while \n actually starts a new line (see this StackExchange anwser for a nice explanation).
I assume that, on windows, it allows you to simply write on the same line until the program exits.
Sadly it could work at least with some terminals on UNIXes but not necessarily on every terminals...
As a work around, you could probably use the \b character which deletes the last caracter of the line, like the [backspace] key.

Printing unicode charcter in windows

I am trying to create file with Unicode character 662f on windows (via Perl or python, anything is fine for me ) . on Linux I am able to get chr 是 , but on windows I am getting this character 是 , and some how I am not able to get that file name as 是.
Python code -
import sys
name = unichr(0x662f)
print(name.encode('utf8').decode(sys.stdout.encoding))
perl code -
my $name .= chr(230).chr(152).chr(175); ##662f
print 'file name ::'. "$name"."txt";
File manipulation in Perl on Windows (Unicode characters in file name)
In Perl on Windows, I use Win32::Unicode, Win32::Unicode::File and Win32::Unicode::Dir. They work perfectly with Unicode characters in file names.
Just mind that Win32::Unicode::File::open() (and new()) have a reversed argument order compared Perl's built-in open() - mode comes first.
You do not need to encode the characters manually - just insert them as they are (if your Perl script is in UTF-8), or using the \x{N} notation.
Printing out Unicode characters on Windows
Printing Unicode into console on Windows is another problem. You can't use cmd.exe. Instead use PowerShell ISE. The drawback of the ISE is that it's not a console - scripts can't take input from keyboard thru STDIN.
To get Unicode output, you need to do set the output encoding to UTF-8 in every PowerShell ISE that's started. I suggest doing so in the startup script.
Procedure to have PowerShell ISE default to Unicode output:
1) In order for any user PowerShell scripts to be allowed to run, you first need to do:
Set-ExecutionPolicy RemoteSigned
2) Edit or create your Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1 to something like:
perl -w -e "print qq!Initializing the console with Perl...\n!;"
[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8;
The short Perl command is there as a trick to allow the System.Console property be modified. Without it, you get an error when setting the OutputEncoding.
If I recall correctly, you also have to change the font to Consolas.
Even when the Unicode characters print out fine, you may have trouble including them in command line arguments. In these cases I've found the \x{N} notation works. The Windows Character Map utility is your friend here.
(Edited heavily after I rediscovered the regular PowerShell's inability to display most Unicode characters, with references to PowerShell (non-ISE) removed. Now I remember why I started using the ISE...)

How to print japanese utf-8 on console in windows?

#coding=<utf8>
import os
os.popen('chcp 65001')
a = 'こんにちは世界'
print a.decode('utf8')
x = raw_input()
PYTHON 2.6 on Windows 7
It will run in IDLE with no errors.
However when run from the console, it errors and flashes very quickly and I can't read the error message.
How can it be done in windows console?
By the way, doing this with other languages like spanish or portuguese will work fine. It's languages like japanese, russian, greek, hebrew that have this error behavior in the windows console.
*EDIT
as requested I changed to this code:
#coding=<utf8>
import os, sys
os.popen('chcp 65001')
print(sys.stdout.encoding)
x = raw_input('press enter to continue')
a = 'こんにちは世界'
print a.decode('utf8')
x = raw_input()
It will print:
cp437
and then of course, continue on to flash and fail on the decoding bit...
It looks like the popen('chcp 65001') doesn't work in changing the codepage.
I still don't think this is the root of the problem, however it would be helpful to know an efficient way of changing this codepage.
Update
Never mind. The OP is using Windows.
Interestingly changing the encoding declaration to #encoding=<utf8> did not work in Ubuntu.
Original Answer
This worked for me (Ubuntu Jaunty, Python 2.6.2). The only change I made was to the first line declaring the encoding.
# encoding: utf-8
import os
os.popen('chcp 65001')
a = 'こんにちは世界'
print a.decode('utf8')
x = raw_input()

Categories