Прогресс уведомлений в трее из командной строки

Вместо того, чтобы печатать все поля, вы можете напечатать всю строку с $ 0 .

Это может сработать, потому что мы можем изменить поля, назначив им данные

например,

$2=$2*100

обновит второе поле и оставит остальные нетронутыми:

% echo '1 2 3 4' | awk '{$2=$2*100; print $0}'
1 200 3 4

Мы можем уменьшить это поле, сделав использование значений по умолчанию; например, print сам по себе напечатает $ 0

awk '{$2=$2*100; print}'

Мы даже можем использовать действия по умолчанию:

awk '{$2=$2*100} 1'

Но в целом я рекомендую более длинную версию, потому что другим людям легче читать и понимать ; Удобство сопровождения кода так же важно, как и краткость:

awk '{$2=$2*100; print $0}'
3
05.08.2016, 17:21
1 ответ

Проблема с использованием qdbus org.kde.JobViewServer.requestViewиз сценария оболочки заключается в том, что он предназначен для удаления уведомления при выходе запрашивающего клиента D-Bus, поэтому такие инструменты, как dbus-sendи qdbusне будут работать, потому что они завершают работу сразу после вызова requestView.

Если вы используете qdbusviewerдля создания запроса, вы можете поиграться с подобными вызовами, и это сработает, но я сомневаюсь, что вы найдете что-то готовое, что можно было бы вызвать из сценария оболочки, чтобы держать соединение открытым для вас.

# Assuming qdbusviewer got /JobViewServer/JobView_15 from the call...

qdbus org.kde.kuiserver /JobViewServer/JobView_15 org.kde.JobViewV2.setInfoMessage 'Frobnicating the foobles...'
qdbus org.kde.kuiserver /JobViewServer/JobView_15 org.kde.JobViewV2.setDescriptionField 1 Cromulence fair
qdbus org.kde.kuiserver /JobViewServer/JobView_15 org.kde.JobViewV2.setPercent 25
qdbus org.kde.kuiserver /JobViewServer/JobView_15 org.kde.JobViewV2.setSpeed 200
qdbus org.kde.kuiserver /JobViewServer/JobView_15 org.kde.JobViewV2.setTotalAmount 100000 bytes
qdbus org.kde.kuiserver /JobViewServer/JobView_15 org.kde.JobViewV2.setProcessedAmount 200 bytes

qdbus org.kde.kuiserver /JobViewServer/JobView_15 org.kde.JobViewV2.terminate 'Received Ctrl+C'

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

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

#!/usr/bin/env python

# This line opts into some Python 3.x features if you run Python 2.x
# and must go at the top of the file because it changes how the file is parsed.
# (Specifically, the Python 3.x print() syntax and sane division)
from __future__ import print_function, division

# These lines are analogous to `source` in a shell script
# The `import` statement searches `sys.path` for the requested packages
import fnmatch, os, subprocess, time

# I'm not sure what package you'll need on OpenSUSE, but this comes from
# python-dbus on Debian, *buntu, and Mint.
import dbus

# -- Get a handle for the D-Bus API to create a new Job --

session_bus = dbus.SessionBus()

# A simple little helper function to paper over some complexity
# See Also: https://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html
def get_dbus_interface(name, path, interface):
    obj = session_bus.get_object(name, path)
    return dbus.Interface(obj, dbus_interface=interface)

create_handle = get_dbus_interface(
    'org.kde.kuiserver', '/JobViewServer', 'org.kde.JobViewServer')

# -- Create a Job and get a handle to manipulate it --

# requestView takes (appName, appIconName, capabilities)
# https://lists.freedesktop.org/archives/xdg/2008-April/009410.html
# ...but according to the source code, capabilities never got hooked up, so
# the pause and stop buttons will always be there, whether or not you're
# listening for them. (And stop will always kill the popup.)
request_path = create_handle.requestView('MyTestApp', 'download', 0)
request_handle = get_dbus_interface(
    'org.kde.kuiserver', request_path, 'org.kde.JobViewV2')

# -- Set up a fake task for demonstration purposes --
files = os.listdir('/etc')  # NOTE: Check out os.walk() for recursive
file_count = len(files)
wait_per_file = 5.0 / file_count  # Add 2 seconds to the total runtime

# -- Configure the bits of the popup that won't change in our example --
request_handle.setInfoMessage('Echoing files in /etc')
request_handle.setTotalAmount(file_count, 'files')
request_handle.setSpeed(200 * 1024**4)  # 200 TiB/s

# -- Do our fake work --

# NOTE: In Python, indentation outside of () and [] is significant
try:
    for position, filename in enumerate(files):
        # Visible in the collapsed view
        request_handle.setPercent((position / file_count) * 100)
        request_handle.setDescriptionField(0, 'Source', filename)
        request_handle.setDescriptionField(1, 'Destination', filename)

        # These are for the expanded view
        request_handle.setProcessedAmount(position, 'files')

        # Here's some fake work so you can see how to call subprocesses
        subprocess.call(['echo', filename])
        time.sleep(wait_per_file)

    # Set the final state of the popup that will be left behind
    request_handle.setDescriptionField(0, "", "Completed successfully.")
    request_handle.clearDescriptionField(1)
    request_handle.terminate("All done")
except KeyboardInterrupt:
    print("Ctrl+C Pressed")
    request_handle.setDescriptionField(0, "Cancelled", "Ctrl+C Pressed")
    request_handle.clearDescriptionField(1)
    request_handle.terminate("Cancelled from outside")
finally:
    # This gets called no matter what
    print("Doing fake cleanup")

print("%s of the files were *.conf" % len(fnmatch.filter(files, '*.conf')))
2
27.01.2020, 21:26

Теги

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