I am trying to change the keyboard language in python (windows). I have searched everywhere for a way to do it and the most common answer is
import win32api
win32api.LoadKeyboardLayout('00000409',1) # to switch to english
win32api.LoadKeyboardLayout('00000401',1) # to switch to arabic
But the only thing this code does is add another language to the current list of languages on my pc - it doesn't change the language's keyboard (when I try typing something after I ran the script it keeps typing in the same language).
BTW, I am using windows
Thank you in advance for any help!
שלום נגה.
I managed to do it with keyboard events & shortcut assignment.
go to windows 7 > control panel > "text services and input language" (or right-click langauge-bar > settings)
assign keys for the uni-directional language. e.g. "To English", and "To Hebrew". I've chosen Alt-Shift-7 and Alt-Shift-8, because they're rarely used elsewhere.
from your app, send the key combination for the appropriate language, when needed.
Note:
if "your app" is an external utility (I wrote mine in Python), then it must NOT invoke a window, otherwise /your-app/ will steal the focus, and will get the language change. in python I solved it by using a GUI-less pyw script filename. (or invoke the script with pythonw.exe)
this article shows how to send keyboard events in python:
https://python-decompiler.com/article/2012-11/how-to-generate-keyboard-events-in-python
This is works for me
from win32con import WM_INPUTLANGCHANGEREQUEST
from win32gui import GetForegroundWindow
from win32api import SendMessage
if SendMessage( GetForegroundWindow(), WM_INPUTLANGCHANGEREQUEST, 0, 0x4090409) == 0:
print('設定英文鍵盤成功!')
Related
I want to know how to refresh the console of my program as if it was just started. Let's say that my code consists of an infinite loop and it has multiple instances of the print() function within itself, I want, every time that loops returns to its start, all the new data whether there is some change or not to get outputted on the same place of the data that has been outputted the last time.
I have been reading about similar problems others have posted and the answers usually revolve around the idea of using \r, when I do that, however, it's always messy and the strings are either printed halfway or there are missing characters. On Replit there is a module called "replit" and there is a function there called clear() that basically performs what I need, but I don't seem to find it when I am using PyCharm, which means that it is perhaps something that works exclusively within the Replit environment. So I am asking, is there something similar in the standard python library that I can use? Thanks
You can use:
import os
command = 'cls' #for windows
os.system(command)
example:
print('hi')
os.system(command)
print('hi')
Output:
hi
For windows you need:
command = 'cls'
For all others it is:
command = 'clear'
To account for any OS you could use:
import os
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If computer is running windows use cls
command = 'cls'
os.system(command)
clearConsole()
There is nothing standard in Python to do it, because Python is not aware of whatever console you are using.
When you call print it is actually writing to a file called "standard output".
It can go to a console if you are running your program in a console (like windows cmd, Linux or Mac OS terminal app, or whatever PyCharm uses).
But it can also be redirected to a regular file by the user of your program.
So there is no standard way.
\r is "carriage return" character. On consoles that respect it, it will set your output position to the beginning of the current line, but will not erase any text already printed on that line (usually).
One way to print text in specific places on the screen is PyCurses.
It supports many consoles and figures out which one you are using automatically.
You can do something like this:
import curses
stdscr = curses.initscr()
stdscr.addstr(x, y, "my string")
By using the addstr isntead of print, you can choose the exact position the text will appear, with X and Y coordinates (first two parameters).
Read the documentation for more ways to manipulate text display with this library.
How exactly can I change the theme of a mac terminal using python. I have a command line program and I want to have a specific theme for the terminal (other than the basic theme) as my command-line program starts.
You can use the Python subprocess module to call an AppleScript:
#!/usr/bin/python
import subprocess
def asrun(ascript):
osasc = subprocess.Popen(['osascript', '-'],
stdin = subprocess.PIPE, stdout=subprocess.PIPE)
return osasc.communicate(ascript)[0]
def asquote(astr):
ascrpt = astr.replace('"', '" & quote & "')
return '"{}"'.format(ascrpt)
ascript = '''
tell application "Terminal"
activate
set current settings of tabs of windows to settings set "Pro"
end tell
'''
asrun(ascript)
This will change all of the windows and tabs you currently have open. If you want it do change just one and not the others, or change the window when you launch terminal that's fairly easy to do. It's just a matter of determining which window or tab you want to change and how you are calling the script in the first place. This should give you an idea though of the basic means of how it works — so I've left this example fairly minimal so you can understand the basics of it.
To change the profile, substitute "Pro" with any profile name (even custom versions you've created) that are listed in Terminal.app.
Given a string, I'd like to be able to send a set of keystrokes to type that string and I'd like to be able to do it in python on OSX (in python because it's part of a larger project already written in python, on OSX because I am trying to port it to OSX).
I'm able to do this now using pyobj like so (this is somewhat simplified):
from Quartz import *
CHAR_TO_SEQUENCE = {
'a':[(0, True), (0, False)]
}
def send_string(string):
for c in string:
sequence = CHAR_TO_SEQUENCE[c]
for keycode, key_down in sequence:
CGEventPost(kCGSessionEventTap, CGEventCreateKeyboardEvent(None, keycode, key_down))
and I've fleshed out CHAR_TO_SEQUENCE to include most of what I can type on my keyboard, which took a while and was tedious.
The problems with this are:
- It only works while the keyboard has the ANSII standard layout. If someone uses a french keyboard, for example, it will type the wrong things.
- It requires this ridiculous table.
I found this general solution for OSX but couldn't figure out how to apply it to python:
How to convert ASCII character to CGKeyCode?
The API mentioned there doesn't seem to be available via pyobj (or maybe I just couldn't figure out the import path).
I've seen some suggestions to set CGEventKeyboardSetUnicodeString to the desired string and not worry about the keycode. But I wasn't able to figure out how to call CGEventKeyboardSetUnicodeString from python (I can't get the arguments right) and it's not clear that this will work because the documentation says that applications can choose to ignore this in favor of the keycode.
Is there a way to do this in python on OSX?
It looks like the Carbon modules don't wrap the TIS* functions, and neither does anything else.
You could extend PyObjC, but it's much simpler to just build a trivial extension module that wraps the two functions you actually need.
Since it was faster to just do it than to explain how to do it, you can get it from https://github.com/abarnert/pykeycode and just do the usual "python setup.py build_ext --inplace" or "sudo python setup.py install", then look at test.py to see how to use it.
http://tinypic.com/r/5dv7kj/7
How can i show the message like in the picture(top right)?
I'm new to linux and now tring to use pygtk to make a client application to show/popup some random hint/mems.
Using traditional winodw is OK,but this one is much more friendly to me.I have tried scanning through the pygtk guide but still missing the solution.Other
Is there any body could give me some hint?Any python GUI libs are also OK.
It's an Ubuntu specific thing called NotifyOSD. There are examples of programming for it here.
Quick and Dirty codes in python
import pynotify
# Only Text Notification
pynotify.init('Basic')
pynotify.Notification("Title", "simple text").show()
# Lets try with an image
pynotify.init('Image')
## Use absolute Path of the photo
pynotify.Notification("Title", "My Photo here!!", "/home/nafis/Pictures/me.png").show()
# Try Markup
pynotify.init("markup") ## all smallerCase "markup"
# but in parameter, first letter capital
pynotify.Notification("Markup",
'''
<b>bold</b>, <i>italic</i>, <u>underline</u>
and even links are supported!
'''
).show()
Also You can use it from shell (I use lubuntu, it works here.)
#!/bin/bash
### try it in terminal
notify-send -t 900 "Title" "Message"
A simple method without any additional packages.
you can execute commands via os.system.
import os
def message(title, message):
os.system(f"notify-send '{title}' '{message}'")
message("Title", "Im message")
I'm making a text adventure, and I want to have pyGame animations and illustrations and a HUD!
How can I insert this console?
Thanks!
I'm pretty sure that's impossible. If you want a console within a Pygame screen then you'll have to write your own, or find one written by someone else (e.g. http://pygame.org/project-pygame-console-287-.html)
For your game, you can use subsurface, for the different screen 'sections'.
Using python 3x will have issues with multiple libraries, that are not precompiled for you. If you can, it will simplify things to Use 2.7 or 2.6. (There is a python2.7 binary, but not on the front page)
A console isn't too hard. You need to break down the components, deciding what you need.
Start with a miniproject, implementing features one at a time.
keyboard input, print letters to console
render text from a string
blit cached text. will have demo code later, if you are interested
dict() of strings, for commands, with values of function names.
draw the last 10 lines of text
up = scroll through command history
allow command aliases, like "n" and "north" will point to move_north
Implement this using a class: Command() . Which stores a list of all aliases.
commands = { "n" : move_north, "s" : move_south, "fps" : toggle_fps, "help" : print_help }
On enter, call the dict's value, if key exists:
if cmd in commands:
commands[cmd]()
# same as commands["n"]()
You could even have the console's print_help() use the function docstrings.