Starting a Python script thru a shortcut - how to detect the SHIFT key being pressed while doing it ?

Hello all,

I've got a Python 3 script which I start by clicking a shortcut on the desktop. I would like to be able to have the script show a dialog (with options) when I click the link while the SHIFT, CTRL or ALT key is being held down.

Question: is this possible, and if so, how.

Regards, Rudy Wieser

Reply to
R.Wieser
Loading thread data ...

On Fri, 14 Feb 2020 14:19:09 +0100, "R.Wieser" declaimed the following:

First question: is this a GUI application (Tkinter, wxPython, other), or a console application?

Potential difficulties:

First: any modifier keys held down when clicking on an icon would be intercepted and processed by the window/file manager/launcher itself -- so that manager would need features to allow different command lines when launching an application based on modifier keys so the command lines could set option flags (Python sys.argv contents) allowing the application to then take different routes.

If it is a console application, all input is via sys.stdin, and that channel is normally in "cooked" mode -- you receive a line of processed text when is pressed. No indicator of modifier and base key. In fact, most console I/O does NOT generate anything for modifier keys on their own -- only modifier in conjunction with some other key. Converting the channel to "raw" mode /might/ let you detect modifier keys -- but I suspect not; mostly it lets you catch keys without waiting for and maybe without echoing to the console, catch / as characters. Essentially, if it doesn't show up as a "character" in the character map, it is not passed to the application. At the lowest level, you might get a byte indicating modifier keys and a second byte with the keyboard keycode.

If it is a GUI application, the event loop may be able to detect modifier keys on their own (M$ Windows: pressing the key activates the application menu bar shortcuts [underlined letter] so entering one of those letters next will open the menu). You will have to study the details of the GUI library being used. Note that this does not result in activation on launch -- the app has to start first and /then/ detect a modifier key.

cf:

formatting link
formatting link

--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber

It would be easier to have a second shortcut using an argument to instruct it to bring up the dialog.

---druck

Reply to
druck

Dennis,

Hello again. :-)

Both. By default it would run silently on the background and exit when done. But when the SHIFT key is pressed I would like to display a (Tkinter) dialog (showing options to how to proceede)

[snip]

I'm aware of those, but have no idea how to proceed. Hence my post.

The easiest solution would be a simple "is the SHIFT key down ?" check, which would work regardless of how the script is started (thru a shortcut, by doubleclicking the script itself, thru the console or otherwise) or which mode it runs in (very doable under Windows, but Linux doesn't seem to like and thus not offer it)

Another possibility would be that Linux notices the modifier when the shortcut is clicked, and adds a switch to the call of the program (a long shot, but hey).

One possible method would be to start the script with a delay and in that time check for a (repeated) keydown event. But I dislike having such a guessed "well, this should be longer than the autorepeat" delay. And it most likely only works for "real" keys, not modifiers like SHIFT, CTRL and ALT.

As for those links ? I do not really like having to install a different version of Python just to be able to check for a key being down. Sorry. (I saw that, IIRC, PyGames offered something similar).

Regards, Rudy Wieser

Reply to
R.Wieser

druck,

:-) Yeah, thought of that too.

Or having a single link on the desktop which starts the script with a certain argument (to bypass the dialog), and just doubleclick the script itself (which ofcourse starts the script without any arguments) when I want the dialog to appear (it wouldn't clutter the desktop).

But for some reason the idea of being able to use a single entrypoint (the shortcut) to have two (or more) different things happen appeals to me.

Thanks for the suggestion though.

Regards, Rudy Wieser

Reply to
R.Wieser

On Fri, 14 Feb 2020 21:05:30 +0100, "R.Wieser" declaimed the following:

wxPython is not a "different version of Python". It is a /library/ used by Python, just as Tkinter is a library.

In either case, the application likely has to start AS a GUI application, meaning it will have an event loop and /focus/ in order to detect the keyboard state. It could then, if no modifiers are down, destroy the event loop and associated GUI window, and revert to a background task with no user interface features.

Probably easier to set up two shortcut icons -- both of which invoke the same application, but which have different start-up command lines. One results in direct/background execution, the other triggers setting up the GUI.

wulfraed@ElusiveUnicorn:~$ cat background.py #!/usr/bin/env python3 import sys import os.path

print(sys.argv[0])

fname = os.path.basename(sys.argv[0])

if fname == "background.py": print("Not GUI?") elif fname == "config.py": print("Do GUI?") else: print("I don't know what to do!")

wulfraed@ElusiveUnicorn:~$ ln -s background.py config.py wulfraed@ElusiveUnicorn:~$ ls -l total 0

-rwxrwxrwx 1 wulfraed wulfraed 254 Feb 14 19:41 background.py lrwxrwxrwx 1 wulfraed wulfraed 13 Feb 14 19:41 config.py -> background.py wulfraed@ElusiveUnicorn:~$ ./background.py ./background.py Not GUI? wulfraed@ElusiveUnicorn:~$ ./config.py ./config.py Do GUI? wulfraed@ElusiveUnicorn:~$

--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber

Dennis,

My apologies, I'll look into it.

:-) Yeah, I thought of that one too. Clutters the desktop though, which is something I could do without.

So, as the person I am I wanted to explore possible other solutions. Using a modifier key is one of them*, and rather elegant if you ask me.

*with part of my question being if the OS/shortcut has any support for it - which would be the best-and-easiest solution - but which it doesn't seem to have.

Besides, for me the travel towards a result is rather enjoyable (I'm learning from it), and I have no problem with putting a bit of time and energy into it.

Regards, Rudy Wieser

Reply to
R.Wieser

Unfortunately as has been pointed out, but not particularly clearly, when invoking a desktop launcher icon you are not talking to the application, you are talking to the window manager. And or a few other apps like caja in MATE

Nothing you do inside the application is useful in this respect.

You have to customise the window manager.

formatting link

is a top level place to start for the Marco windowing system used by MATE desktops

--
Future generations will wonder in bemused amazement that the early  
twenty-first century?s developed world went into hysterical panic over a  
globally average temperature increase of a few tenths of a degree, and,  
on the basis of gross exaggerations of highly uncertain computer  
projections combined into implausible chains of inference, proceeded to  
contemplate a rollback of the industrial age. 

Richard Lindzen
Reply to
The Natural Philosopher

TNP,

Thats why I said: [quote] Another possibility would be that Linux notices the modifier when the shortcut is clicked, and adds a switch to the call of the program [/quote]

That would be a possibility too, but a change of that magnitude is not something I'm currently willing to pursue.

Thanks for the suggestion though.

Regards, Rudy Wieser

Reply to
R.Wieser

On Sat, 15 Feb 2020 09:10:12 +0100, "R.Wieser" declaimed the following:

It's also quite likely specific to the manager in use...

--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber

Dennis,

Besides that, yes.

By the way, my [quote] One possible method would be to start the script with a delay and in that time check for a (repeated) keydown event. [/quote] idea doesn't pan out: no repeated keydown events. :-\ (or at least, they do not show up using "bind")

Currently looking into capturing a key up or down event using the tkinter root window (something must be there to receive focus) which self-closes after a second. Don't really like the need for a visible window, but hey, that can't be helped.

Regards, Rudy Wieser

Reply to
R.Wieser

On Sat, 15 Feb 2020 18:30:24 +0100, "R.Wieser" declaimed the following:

Probably not helpful... Especially for the modifier keys (as a test, I just held down the key and only got one toggling of the menu bar shortcuts -- not a toggle, delay, toggle, toggle, toggle... {Win10, but I suspect most OS's handle the modifier keys the same way -- they may generate an event once, but after that they are "state information" retrieved using a different method})

formatting link

From Tkinter source """ def bind(self, sequence=None, func=None, add=None): """Bind to this widget at event SEQUENCE a call to function FUNC.

SEQUENCE is a string of concatenated event patterns. An event pattern is of the form where MODIFIER is one of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4, Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3, B3, Alt, Button4, B4, Double, Button5, B5 Triple, Mod1, M1. TYPE is one of Activate, Enter, Map, ButtonPress, Button, Expose, Motion, ButtonRelease FocusIn, MouseWheel, Circulate, FocusOut, Property, Colormap, Gravity Reparent, Configure, KeyPress, Key, Unmap, Deactivate, KeyRelease Visibility, Destroy, Leave and DETAIL is the button number for ButtonPress, ButtonRelease and DETAIL is the Keysym for KeyPress and KeyRelease. Examples are for pressing Control and mouse button 1 or for pressing A and the Alt key (KeyPress can be omitted). An event pattern can also be a virtual event of the form where AString can be arbitrary. This event can be generated by event_generate. If events are concatenated they must appear shortly after each other. """ Note the list of those considered MODIFIER and not DETAIL.

--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber

Dennis,

Duh... I just tested both a character and a modifier key (something I should have done earlier). The first threw a number of repeated keydowns, the latter didn't. Can even understand why. It certainly does throw a wrench in my "start script while having a modifier key down" idea though.

I could ofcourse use one of the character keys, but that could have side effects, as Thonny has already shown me. When I pressed space directly after having clicked the "run" button, the button behaved as having been clicked again. Which is not quite unsuspected ofcourse.

No, I don't think I'm going to use one of the "real" keys as a modifier.

...

I'm afraid that I just understand part of it, and only because I've found (and used) example code for that command. You seem to be indicating that "detail" might be of use for me ? Can you tell how ?

The best I can currently think of is to have the script show a timed window when its started, at which moment I have to either press or release a modifier (or even character) key. Not really user-friendly.

Regards, Rudy Wieser

Reply to
R.Wieser

Autorepeat.

--
Steve O'Hara-Smith                          |   Directable Mirror Arrays 
C:\>WIN                                     | A better way to focus the sun 
The computer obeys and wins.                |    licences available see 
You lose and Bill collects.                 |    http://www.sohara.org/
Reply to
Ahem A Rivet's Shot

Ahem,

One group of keys does, another group doesn't. What are you traying to say ?

Regards, Rudy Wieser

Reply to
R.Wieser

Modifier keys don't repeat only character keys, the modifiers just cause different keycodes to be in the key press event. Run xev to see what I mean.

--
Steve O'Hara-Smith                          |   Directable Mirror Arrays 
C:\>WIN                                     | A better way to focus the sun 
The computer obeys and wins.                |    licences available see 
You lose and Bill collects.                 |    http://www.sohara.org/
Reply to
Ahem A Rivet's Shot

On Sun, 16 Feb 2020 08:41:31 +0100, "R.Wieser" declaimed the following:

Which leads back to ability to read the keyboard "state" (modifier keys) from within you application -- without waiting for a key-down/-up event.

All of which depends on initializing a GUI system (even if nothing is rendered to screen, so long as it captures keyboard focus).

If you read further down in that densely packed text, DETAIL is described as "key-sym" for key-down/-up events... So far as I know, that is the basic value for the key (so might be used to catch "%" -- I don't know Tkinter enough to know if just would be trapped).

The point is that key-down/-up events need a triggering key, and modifiers alone are not such (to my knowledge). As you discovered, a triggering key will activate auto-repeat -- modifiers alone do not.

Really? Consider how many boot sequences have a few seconds in which to catch a key press to stop the default boot sequence. I believe the u-Boot on BBB has a few seconds in which to interrupt it and drop into command line (but one needs to have a raw serial terminal on the debug pins -- not available via SSH). R-Pi doesn't use u-Boot natively, but it can be built for it (not that you need it for YOUR situation -- just pointing out that it can be done)

Not "user-friendly" is one of the Easter eggs on AmigaOS 1.3 (maybe still in 2.x, but removed in 3.x).

That Easter egg required one to hold down both "A" (Amiga) keys, either both shift or both control keys, F10 key, AND eject then insert a floppy disk! Without the floppy eject/insert, holding those modifiers and pressing the Fx keys would display messages listing parts of the Amiga hardware/software and the engineer behind that part. The floppy activity then put up a message to the effect "We created Amiga; it up" ("they" likely meaning Commodore).

--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber

Ahem,

I'm sorry, but the part before the comma has got zero to do with the part after it.

Yes, I'm (now) aware that modifier keys do not repeat - as I already mentioned in the post you responded to.

No, modifiers do not cause different keycodes. Characters, yes. Keycodes, no.

I'm sorry, but I'm at a loss to what you are trying to tell me here. And I still do not know what that "Autorepeat" response was for. :-|

Regards, Rudy Wieser

Reply to
R.Wieser

Dennis,

Yep. Which doesn't seem possible under Linux. Alas (for me).

I'm afraid I lost sync somewhere along the way there. :-\

Yep, I missed that part. And your explanation to it makes sense to me though. Thanks.

And those are not user-friendly either. Most all of them have timings too short to actually read what you need to do and find the key you need to use (F2 ? F21 ? Ctrl-C ? Other ?). Hence multiple reboots needed. :-( And when the time is long enough it starts to irritate rather quickly (at least with me).

/Especially/ when you are actually waiting for a program to start, and not, as I can do when booting my 'puter , jab the powerbutton, do something else, and only return when it has fully booted.

Yep, that one is nasty. Than again, its designed to be exactly that.

I've got a game here which uses the WASD keys for moving around, together with the mouse for the direction. It also has a certain action, which you can often ony do when moving forward, bound to the "Z" key. A nice finger-twister, especially under "it has to be done /now/" pressure. :-|

Regards, Rudy Wieser

Reply to
R.Wieser

On Sun, 16 Feb 2020 20:49:08 +0100, "R.Wieser" declaimed the following:

I think my very first post on this thread linked to a wxPython call that does just that... But it does mean your application would have to be built using wxPython rather than Tkinter... And you still need to have some sort of window/framework which gains focus...

--
	Wulfraed                 Dennis Lee Bieber         AF6VN 
	wlfraed@ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/
Reply to
Dennis Lee Bieber

ElectronDepot website is not affiliated with any of the manufacturers or service providers discussed here. All logos and trade names are the property of their respective owners.