Как метать икру/инициировать команду после ввода определенной рабочей области

Это Вопросы и ответы связано для Выключения СУПЕР ключа во время полноэкранных приложений. У меня был запрос, чтобы заставить решение работать на определенную рабочую область.

Посмотрите ниже для решения

3
задан 13 April 2017 в 15:24

2 ответа

Так же, как другая опция, с помощью другого метода для указания на текущую область просмотра. Я использовал подобный fuctionality во многих сценариях, a.o. здесь.

import subprocess
import os
import time

def get_res():
    # get resolution
    xr = subprocess.check_output(["xrandr"]).decode("utf-8").split()
    pos = xr.index("current")
    return [int(xr[pos+1]), int(xr[pos+3].replace(",", "") )]

def get_dt():
    # get the current viewport
    vp_data = subprocess.check_output(["wmctrl", "-d"]).decode("utf-8").split()
    dt = [int(n) for n in vp_data[3].split("x")]
    cols = int(dt[0]/res[0])
    curr_vpdata = [int(n) for n in vp_data[5].split(",")]
    curr_col = int(curr_vpdata[0]/res[0])+1; curr_row = int(curr_vpdata[1]/res[1])
    return curr_col+curr_row*cols

res = get_res()
curr_dt1 = None

while True:
    time.sleep(0.5)
    curr_dt2 = get_dt()
    # if we change viewport, do something:
    if curr_dt2 != curr_dt1:
        print(curr_dt2)
        # if we enter viewport3, do something
        if curr_dt2 == 3:
            subprocess.Popen(["gedit"])
    curr_dt1 = curr_dt2

Сценарий обнаруживает оба изменения в области просмотра, а также вводе определенной области просмотра.

  • Если действие должно быть сделано на изменении в областях просмотра, замените команду печати в:

    if curr_dt2 != curr_dt1:
        print(curr_dt2)
    

    ... другой командой (subprocess.popen())

  • Если действие должно поместить во ввод g определенную область просмотра, замените команду в:

        if curr_dt2 == 3:
            subprocess.Popen(["gedit"])
    

    ... другим. Если процесс должен быть уничтожен при отъезде рабочей области добавьте раздел:

        if all([curr_dt1 == 3 curr_dt2 != 3]):
            subprocess.Popen(["<killcommand>"])
    
2
ответ дан 1 December 2019 в 15:35

Введение

Существенный рабочий процесс этого решения должен иметь сценарий обертки, который запускает команду пользователя после ввода рабочей области и отправляет sigterm в него, когда пользователь вводит рабочую область не в список. Это лучше всего используется с командами, которые могут использоваться в качестве автономных приложений и могут быть безопасно завершены без потери информации

Использование

Как показано -h опция

usage: workspace_command_limiter.py [-h] -w WORKSPACES -c COMMAND

Runs user-defined command __upon__ entering user-defined set of workspaces.
For instance ./workspace_command_limiter.py -w 1,2,3 -c "python
/home/user/some_script.py" This is intended to serve only as launcher for a
command when user switches to their desired workspace, so consider carefully
which command you want to use. NOTE: This script does run everything from
shell, so you are here implicitly trusted not to use any command that may
break your system. I'm not responsible for your stupidity :)

optional arguments:
  -h, --help            show this help message and exit
  -w WORKSPACES, --workspaces WORKSPACES
                        coma-separated list(without spaces) of workspaces
  -c COMMAND, --command COMMAND
                        quoted command to be spawned,when switch to workspace
                        occurs

В контексте disable_super_key.py сценарий, это должно работать как так

./workspace_command_limiter.py -w 1,2 -c "python ./disable_super_key.py"

Отметьте, это в этом примере, ./ указывает, что оба сценария находятся в том же каталоге.

Источник сценария

Также доступный на GitHub

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Serg Kolo , contact: 1047481448@qq.com 
Date: August 24th, 2016
Purpose: Runs user-requested command only on specific workspaces
Tested on: Ubuntu 16.04 LTS , Unity desktop

The MIT License (MIT)

Copyright © 2016 Sergiy Kolodyazhnyy <1047481448@qq.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
"""


# Just in case the user runs 
# the script with python 2, import
# print function
from __future__ import print_function
import gi
gi.require_version('Gdk', '3.0')
from gi.repository import Gio,Gdk
from time import sleep
import subprocess
import argparse 
import signal
import os
import sys

"""Set debug=True to see errors and verbose output"""
debug=False

def gsettings_get(schema,path,key):
    """Get value of gsettings schema"""
    if path is None:
        gsettings = Gio.Settings.new(schema)
    else:
        gsettings = Gio.Settings.new_with_path(schema,path)
    return gsettings.get_value(key)

def run_cmd(cmdlist):
    """ Reusable function for running shell commands"""
    try:
        stdout = subprocess.check_output(cmdlist)
    except subprocess.CalledProcessError:
        if debug: print(">>> subprocess:",cmdlist)
        sys.exit(1)
    else:
        if stdout:
            return stdout

def enumerate_viewports():
    """ generates enumerated dictionary of viewports and their
        indexes, counting left to right """
    schema="org.compiz.core"
    path="/org/compiz/profiles/unity/plugins/core/"
    keys=['hsize','vsize']
    screen = Gdk.Screen.get_default()
    screen_size=[ screen.get_width(),screen.get_height()]
    grid=[ int(str(gsettings_get(schema,path,key))) for key in keys]
    x_vals=[ screen_size[0]*x for x in range(0,grid[0]) ]
    y_vals=[screen_size[1]*x for x in range(0,grid[1]) ]

    viewports=[(x,y)  for y in y_vals for x in x_vals ]

    return {vp:ix for ix,vp in enumerate(viewports,1)}

def get_current_viewport():
    """returns tuple representing current viewport, 
       in format (width,height)"""
    vp_string = run_cmd(['xprop', '-root', 
                         '-notype', '_NET_DESKTOP_VIEWPORT'])
    vp_list=vp_string.decode().strip().split('=')[1].split(',')
    return tuple( int(i)  for i in vp_list )


def parse_args():
    intro="""
    Runs user-defined command __upon__ entering user-defined set of
    workspaces. For instance 
    ./workspace_command_limiter.py -w 1,2,3 -c "python /home/user/some_script.py"
    This is intended to serve only as launcher for a command when user switches
    to their desired workspace, so consider carefully which command you want to use.
    NOTE: This script does run everything from shell, so you are here implicitly trusted
    not to use any command that may break your system. I'm not responsible for your 
    stupidity :) 
    """
    parser = argparse.ArgumentParser(description=intro)
    parser.add_argument(
           "-w","--workspaces",
           action='store',
           type=str, 
           help="coma-separated list(without spaces) of workspaces",
           required=True
           )

    parser.add_argument(
           "-c","--command",
           action='store',
           type=str, 
           help="quoted command to be spawned,when switch to workspace occurs",
           required=True
           )
    return parser.parse_args()


def main():
   """ Defines entry point of the program """
   args = parse_args()
   workspaces = [ int(wp) for wp in args.workspaces.split(',') ]
   if debug: print('User requested workspaces:',workspaces)
   pid = None
   proc = None

   while True:
       sleep(0.25)
       viewports_dict=enumerate_viewports()
       current_viewport = get_current_viewport()
       current_vp_number = viewports_dict[current_viewport]
       try:
           if current_vp_number in workspaces:
               if not pid:
                   proc = subprocess.Popen("exec " + args.command,shell=True)
                   pid = proc.pid
                   if debug: print('PID:',pid,'Spawned:',args.command)
           else:
               if pid:
                   if debug: print('killing pid:',pid)
                   proc.terminate()
                   proc = None
                   pid = None
       except:
             if debug: print("Unexpected error:", sys.exc_info()[0])
             if proc:
                proc.terminate() 
if __name__ == '__main__':
    main()
3
ответ дан 1 December 2019 в 15:35

Другие вопросы по тегам:

Похожие вопросы: