Im trying to change the keyboard type on mac and I generated a script using chatgpt, however neither I or chatgpt can figure out the problem.
Here is the code:
import objc
from Foundation import NSBundle, NSArray
def change_keyboard_layout(layout_id):
# Load the HIToolbox bundle
bundle = NSBundle.bundleWithIdentifier_(‘com.apple.HIToolbox’)
# Define the functions we need to use from HIToolbox
functions = [
('TISCopyInputSourceForLanguage', b'@^v@'),
('TISSelectInputSource', b'i@')
]
# Load the functions into the global namespace
objc.loadBundleFunctions(bundle, globals(), functions)
# Call the TISCopyInputSourceForLanguage function
input_source = TISCopyInputSourceForLanguage(layout_id, None)
if input_source is None:
print(f"No input source found for {layout_id}")
return
# Call the TISSelectInputSource function
result = TISSelectInputSource(input_source)
if result == 0:
print(f"Successfully changed keyboard layout to {layout_id}")
else:
print(f"Failed to change keyboard layout to {layout_id}")
Example usage: change to the U.S. keyboard layout
change_keyboard_layout(“en”)
Tried restructuring
SDXO is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.