{"id":21534829,"url":"https://github.com/netinvent/command_runner","last_synced_at":"2025-04-05T14:04:01.275Z","repository":{"id":39638215,"uuid":"322258425","full_name":"netinvent/command_runner","owner":"netinvent","description":"Substitute for subprocess that handles all hassle that comes from different platform and python versions, and allows live stdout and stderr capture for background job/interactive GUI programming ;)","archived":false,"fork":false,"pushed_at":"2025-03-14T13:42:25.000Z","size":280,"stargazers_count":41,"open_issues_count":3,"forks_count":5,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-29T13:06:50.309Z","etag":null,"topics":["linux","popen","python","subprocess","timeout","windows"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/netinvent.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-12-17T10:23:12.000Z","updated_at":"2025-03-14T13:42:29.000Z","dependencies_parsed_at":"2023-12-27T22:26:30.156Z","dependency_job_id":"b5ae8b5f-fee0-4f2b-85c7-70b3879296b8","html_url":"https://github.com/netinvent/command_runner","commit_stats":{"total_commits":365,"total_committers":2,"mean_commits":182.5,"dds":0.005479452054794498,"last_synced_commit":"80ce32ee9f61a6663b7cd52ec2864427afb9f31b"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/netinvent%2Fcommand_runner","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/netinvent%2Fcommand_runner/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/netinvent%2Fcommand_runner/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/netinvent%2Fcommand_runner/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/netinvent","download_url":"https://codeload.github.com/netinvent/command_runner/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247345850,"owners_count":20924102,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["linux","popen","python","subprocess","timeout","windows"],"created_at":"2024-11-24T03:12:47.937Z","updated_at":"2025-04-05T14:04:01.254Z","avatar_url":"https://github.com/netinvent.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# command_runner\n# Platform agnostic command execution, timed background jobs with live stdout/stderr output capture, and UAC/sudo elevation\n\n[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](https://opensource.org/licenses/BSD-3-Clause)\n[![Percentage of issues still open](http://isitmaintained.com/badge/open/netinvent/command_runner.svg)](http://isitmaintained.com/project/netinvent/command_runner \"Percentage of issues still open\")\n[![Maintainability](https://api.codeclimate.com/v1/badges/defbe10a354d3705f287/maintainability)](https://codeclimate.com/github/netinvent/command_runner/maintainability)\n[![codecov](https://codecov.io/gh/netinvent/command_runner/branch/master/graph/badge.svg?token=rXqlphOzMh)](https://codecov.io/gh/netinvent/command_runner)\n[![linux-tests](https://github.com/netinvent/command_runner/actions/workflows/linux.yaml/badge.svg)](https://github.com/netinvent/command_runner/actions/workflows/linux.yaml)\n[![windows-tests](https://github.com/netinvent/command_runner/actions/workflows/windows.yaml/badge.svg)](https://github.com/netinvent/command_runner/actions/workflows/windows.yaml)\n[![GitHub Release](https://img.shields.io/github/release/netinvent/command_runner.svg?label=Latest)](https://github.com/netinvent/command_runner/releases/latest)\n\n\ncommand_runner's purpose is to run external commands from python, just like subprocess on which it relies, \nwhile solving various problems a developer may face among:\n   - Handling of all possible subprocess.popen / subprocess.check_output scenarios / python versions in one handy function without encoding / timeout hassle\n   - Allow stdout/stderr stream output to be redirected to callback functions / output queues / files so you get to handle output in your application while commands are running\n   - Callback to optional stop check so we can stop execution from outside command_runner\n   - Callback with optional process information so we get to control the process from outside command_runner\n   - Callback once we're finished to easen thread usage\n   - Optional process priority and io_priority settings\n   - System agnostic functionality, the developer shouldn't carry the burden of Windows \u0026 Linux differences\n   - Optional Windows UAC elevation module compatible with CPython, PyInstaller \u0026 Nuitka\n   - Optional Linux sudo elevation compatible with CPython, PyInstaller \u0026 Nuitka\n   - Optional heartbeat for command execution\n\nIt is compatible with Python 2.7+, tested up to Python 3.12 (backports some newer functionality to Python 3.5) and is tested on both Linux and Windows.\nIt is also compatible with PyPy Python implementation.\n...and yes, keeping Python 2.7 compatibility has proven to be quite challenging.\n\n## command_runner\n\ncommand_runner is a replacement package for subprocess.popen and subprocess.check_output\nThe main promise command_runner can do is to make sure to never have a blocking command, and always get results.\n\nIt works as wrapper for subprocess.popen and subprocess.communicate that solves:\n   - Platform differences\n      - Handle timeouts even for windows GUI applications that don't return anything to stdout\n   - Python language version differences\n      - Handle timeouts even on earlier Python implementations\n      - Handle encoding even on earlier Python implementations\n   - Keep the promise to always return an exit code (so we don't have to deal with exit codes and exception logic at the same time)\n   - Keep the promise to always return the command output regardless of the execution state (even with timeouts, callback interrupts and keyboard interrupts)\n   - Can show command output on the fly without waiting the end of execution (with `live_output=True` argument)\n   - Can give command output on the fly to application by using queues or callback functions\n   - Catch all possible exceptions and log them properly with encoding fixes\n   - Be compatible, and always return the same result regardless of platform\n\ncommand_runner also promises to properly kill commands when timeouts are reached, including spawned subprocesses of such commands.\nThis specific behavior is achieved via psutil module, which is an optional dependency.\n\n   \n### command_runner in a nutshell\n\n### In a nutshell\n\nInstall with `pip install command_runner`\n\nThe following example will work regardless of the host OS and the Python version.\n\n```python\nfrom command_runner import command_runner\n\nexit_code, output = command_runner('ping 127.0.0.1', timeout=10)\n```\n\n\n## Advanced command_runner usage\n\n\n### Special exit codes\n\nIn order to keep the promise to always provide an exit_code, special exit codes have been added for the case where none is given.\nThose exit codes are:\n\n- -250 : command_runner called with incompatible arguments\n- -251 : stop_on function returned True\n- -252 : KeyboardInterrupt\n- -253 : FileNotFoundError, OSError, IOError\n- -254 : Timeout\n- -255 : Any other uncatched exceptions\n\nThis allows you to use the standard exit code logic, without having to deal with various exceptions.\n\n### Default encoding\n\ncommand_runner has an `encoding` argument which defaults to `utf-8` for Unixes and `cp437` for Windows platforms.\nUsing `cp437` ensures that most `cmd.exe` output is encoded properly, including accents and special characters, on most locale systems.\nStill you can specify your own encoding for other usages, like Powershell where `unicode_escape` is preferred.\n\n```python\nfrom command_runner import command_runner\n\ncommand = r'C:\\Windows\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe --help'\nexit_code, output = command_runner(command, encoding='unicode_escape')\n```\n\nEarlier subprocess.popen implementations didn't have an encoding setting so command_runner will deal with encoding for those.   \nYou can also disable command_runner's internal encoding in order to get raw process output (bytes) by passing False boolean.\n\nExample:\n```python\nfrom command_runner import command_runner\n\nexit_code, raw_output = command_runner('ping 127.0.0.1', encoding=False)\n```\n\n### On the fly (interactive screen) output\n\n**Note: for live output capture and threading, see stream redirection. If you want to run your application while command_runner gives back command output, the best way to achieve this is using queues / callbacks.**\n\ncommand_runner can output a command output on the fly to stdout, eg show output on screen during execution.\nThis is helpful when the command is long, and we need to know the output while execution is ongoing.\nIt is also helpful in order to catch partial command output when timeout is reached or a CTRL+C signal is received.\nExample:\n\n```python\nfrom command_runner import command_runner\n\nexit_code, output = command_runner('ping 127.0.0.1', shell=True, live_output=True)\n```\n\nNote: using live output relies on stdout pipe polling, which has lightly higher cpu usage.\n\n### Timeouts\n\n**command_runner has a `timeout` argument which defaults to 3600 seconds.**  \nThis default setting ensures commands will not block the main script execution.\nFeel free to lower / higher that setting with `timeout` argument.\nNote that a command_runner will try to kill the whole process tree that the command may have generated.\n\n```python\nfrom command_runner import command_runner\n\nexit_code, output = command_runner('ping 127.0.0.1', timeout=30)\n```\n\n#### Remarks on processes termination\n\nWhen we instruct command_runner to stop a process (because of one of the requirements met, example timeouts), using `shell=True` will spawn a shell which will spawn the desired child process. Under MS Windows, there is no direct process tree, so we cannot easily kill the whole process tree.\nWe fixed this by walking processes during runtime. The drawback is that orphaned processes cannot be identified this way.\n\n### Disabling logs / silencing\n\n`command_runner` has it's own logging system, which will log all sorts of error logs.\nIf you need to disable it's logging, just run with argument silent.\nBe aware that logging.DEBUG log levels won't be silenced, by design.\n\nExample:\n```python\nfrom command_runner import command_runner\n\nexit_code, output = command_runner('ping 127.0.0.1', silent=True)\n```\n\nIf you also need to disable logging.DEBUG level, you can run the following code which will required logging.CRITICAL only messages which `command_runner` never does:\n\n```python\nimport logging\nimport command_runner\n\nlogging.getLogger('command_runner').setLevel(logging.CRITICAL)\n```\n\n### Capture method\n\n`command_runner` allows two different process output capture methods:\n\n`method='monitor'` which is default:\n - A thread is spawned in order to check stop conditions and kill process if needed\n - A main loop waits for the process to finish, then uses proc.communicate() to get it's output\n - Pros:\n     - less CPU usage\n     - less threads\n - Cons:\n     - cannot read partial output on KeyboardInterrupt or stop_on (still works for partial timeout output)\n     - cannot use queues or callback functions redirectors\n     - is 0.1 seconds slower than poller method\n     \n\n`method='poller'`:\n - A thread is spawned and reads stdout/stderr pipes into output queues\n - A poller loop reads from the output queues, checks stop conditions and kills process if needed\n - Pros: \n      - Reads on the fly, allowing interactive commands (is also used with `live_output=True`)\n      - Allows stdout/stderr output to be written live to callback functions, queues or files (useful when threaded)\n      - is 0.1 seconds faster than monitor method, is preferred method for fast batch runnings\n - Cons:\n      - lightly higher CPU usage\n\nExample:\n```python\nfrom command_runner import command_runner\n\n\nexit_code, output = command_runner('ping 127.0.0.1', method='poller')\nexit_code, output = command_runner('ping 127.0.0.1', method='monitor')\n```\n\n#### stdout / stderr stream redirection using poller capture method\n\ncommand_runner can redirect the command's stdout and/or stderr streams to different outputs:\n - subprocess pipes\n - /dev/null or NUL\n - files\n - queues\n - callback functions\n\nUnless an output redirector is given for `stderr` argument, stderr will be redirected to `stdout` stream.\nNote that both queues and callback function redirectors require `poller` method and will fail if method is not set.\n\nOutput redirector descriptions:  \n\n- subprocess pipes\n\n  - By default, stdout writes into a subprocess.PIPE which is read by command_runner and returned as `output` variable.\n  - You may also pass any other subprocess.PIPE int values to `stdout` or `stderr` arguments.\n\n- /dev/null or NUL\n\n  - If `stdout=False` and/or `stderr=False` argument(s) are given, command output will not be saved.\n  - stdout/stderr streams will be redirected to `/dev/null` or `NUL` depending on platform.\n  - Output will always be `None`. See `split_streams` for more details using multiple outputs.\n\n- files\n\n  - Giving `stdout` and/or `stderr` arguments a string, `command_runner` will consider the string to be a file path where stream output will be written live.\n  - Examples:\n```python\nfrom command_runner import command_runner\nexit_code, output = command_runner('dir', stdout=r\"C:/tmp/command_result\", stderr=r\"C:/tmp/command_error\", shell=True)\n```\n```python\nfrom command_runner import command_runner\nexit_code, output = command_runner('dir', stdout='/tmp/stdout.log', stderr='/tmp/stderr.log', shell=True)\n```\n  - Opening a file with the wrong encoding (especially opening a CP437 encoded file on Windows with UTF-8 coded might endup with UnicodedecodeError.)\n\n- queues\n\n  - Queue(s) will be filled up by command_runner.\n  - In order to keep your program \"live\", we'll use the threaded version of command_runner which is basically the same except it returns a future result instead of a tuple.\n  - Note: With all the best will, there's no good way to achieve this under Python 2.7 without using more queues, so the threaded version is only compatible with Python 3.3+.\n  - For Python 2.7, you must create your thread and queue reader yourself (see footnote for a Python 2.7 compatible example).\n  - Threaded command_runner plus queue example:\n\n```python\nimport queue\nfrom command_runner import command_runner_threaded\n\noutput_queue = queue.Queue()\nstream_output = \"\"\nthread_result = command_runner_threaded('ping 127.0.0.1', shell=True, method='poller', stdout=output_queue)\n\nread_queue = True\nwhile read_queue:\n    try:\n        line = output_queue.get(timeout=0.1)\n    except queue.Empty:\n        pass\n    else:\n        if line is None:\n            read_queue = False\n        else:\n            stream_output += line\n            # ADD YOUR LIVE CODE HERE\n\n# Now we may get exit_code and output since result has become available at this point\nexit_code, output = thread_result.result()\n```\n  - You might also want to read both stdout and stderr queues. In that case, you can create a read loop just like in the following example.\n  - Here we're reading both queues in one loop, so we need to observe a couple of conditions before stopping the loop, in order to catch all queue output:\n```python\nimport queue\nfrom time import sleep\nfrom command_runner import command_runner_threaded\n\nstdout_queue = queue.Queue()\nstderr_queue = queue.Queue()\nthread_result = command_runner_threaded('ping 127.0.0.1', method='poller', shell=True, stdout=stdout_queue, stderr=stderr_queue)\n\nread_stdout = read_stderr = True\nwhile read_stdout or read_stderr:\n\n    try:\n        stdout_line = stdout_queue.get(timeout=0.1)\n    except queue.Empty:\n        pass\n    else:\n        if stdout_line is None:\n            read_stdout = False\n        else:\n            print('STDOUT:', stdout_line)\n\n    try:\n        stderr_line = stderr_queue.get(timeout=0.1)\n    except queue.Empty:\n        pass\n    else:\n        if stderr_line is None:\n            read_stderr = False\n        else:\n            print('STDERR:', stderr_line)\n    \n    # ADD YOUR LIVE CODE HERE\n\nexit_code, output = thread_result.result()\nassert exit_code == 0, 'We did not succeed in running the thread'\n\n```\n\n- callback functions\n\n  - The callback function will get one argument, being a str of current stream readings.\n  - It will be executed on every line that comes from streams. Example:\n```python\nfrom command_runner import command_runner\n\ndef callback_function(string):\n    # ADD YOUR CODE HERE\n    print('CALLBACK GOT:', string)\n    \n# Launch command_runner\nexit_code, output = command_runner('ping 127.0.0.1', stdout=callback_function, method='poller')\n```\n\n### stdin stream redirection\n\n`command_runner` allows to redirect some stream directly into the subprocess it spawns.\n\nExample code\n```python\nimport sys\nfrom command_runner import command_runner\n\n\nexit_code, output = command_runner(\"gzip -d\", stdin=sys.stdin.buffer)\nprint(\"Uncompressed data\", output)\n```\nThe above program, when run with `echo \"Hello, World!\" | gzip | python myscript.py` will show the uncompressed  string `Hello, World!`\n\nYou can use whatever file descriptor you want, basic ones being sys.stdin for text input and sys.stdin.buffer for binary input.\n\n### Checking intervals\n\nBy default, command_runner checks timeouts and outputs every 0.05 seconds.\nYou can increase/decrease this setting via `check_interval` setting which accepts floats.\nExample: `command_runner(cmd, check_interval=0.2)`\nNote that lowering `check_interval` will increase CPU usage.\n\n### stop_on\n\nIn some situations, you want a command to be aborted on some external triggers.\nThat's where `stop_on` argument comes in handy,\nJust pass a function to `stop_on`, which will be executed every on every `check_interval`. As soon as function result becomes True, execution will halt with exit code -251.\n\nAs a side note, when using `stop_on=my_func`, if `my_func` is cpu/io intensive, you should set `check_interval` to something reasonable, which generally counts in seconds.\n\nExample:\n```python\nfrom command_runner import command_runner\n\ndef some_function():\n    return True if we_must_stop_execution\nexit_code, output = command_runner('ping 127.0.0.1', stop_on=some_function, check_interval=2)\n```\n\n### Getting current process information\n\n`command_runner` can provide an instance of subprocess.Popen of currently run command as external data, in order to retrieve process data like pids.  \nIn order to do so, just declare a function and give it as `process_callback` argument.\n\nExample:\n```python\nfrom command_runner import command_runner\n\ndef show_process_info(process):\n    print('My process has pid: {}'.format(process.pid))\n\nexit_code, output = command_runner('ping 127.0.0.1', process_callback=show_process_info)\n```\n\n### Split stdout and stderr\n\nBy default, `command_runner` returns a tuple like `(exit_code, output)` in which output contains both stdout and stderr stream outputs.\nYou can alter that behavior by using argument `split_stream=True`.\nIn that case, `command_runner` will return a tuple like `(exit_code, stdout, stderr)`.\n\nExample:\n```python\nfrom command_runner import command_runner\n\nexit_code, stdout, stderr = command_runner('ping 127.0.0.1', split_streams=True)\nprint('exit code:', exit_code)\nprint('stdout', stdout)\nprint('stderr', stderr)\n```\n\n### On-exit Callback\n\n`command_runner` allows to execute a callback function once it has finished it's execution.  \nThis might help building threaded programs where a callback is needed to disable GUI elements for example, or make the program aware that execution has finished without the need for polling checks.\n\nExample:\n```python\nfrom command_runner import command_runner\n\ndef do_something():\n    print(\"We're done running\")\n\nexit_code, output = command_runner('ping 127.0.0.1', on_exit=do_something)\n```\n\n### Process and IO priority\n`command_runner` can set it's subprocess priority to 'low', 'normal' or 'high', which translate to 15, 0, -15 niceness on Linux and BELOW_NORMAL_PRIORITY_CLASS and HIGH_PRIORITY_CLASS in Windows.\nOn Linux, you may also directly use priority with niceness int values.\n\nYou may also set subprocess io priority to 'low', 'normal' or 'high'.\n\nExample:\n```python\nfrom command_runner import command_runner\n\nexit_code, output = command_runner('some_intensive_process', priority='low', io_priority='high')\n```\n\n### Heartbeat\nWhen running long commands, one might want to know that the program is still running.    \nThe following example will log a message every hour stating that we're still running our command\n\n```python\nfrom command_runner import command_runner\n\nexit_code, output = command_runner('/some/long/command', timeout=None, heartbeat=3600)\n```\n\n### Other arguments\n\n`command_runner` takes **any** argument that `subprocess.Popen()` would take.\n\nIt also uses the following standard arguments:\n - command (str/list): The command, doesn't need to be a list, a simple string works\n - valid_exit_codes (list): List of exit codes which won't trigger error logs\n - timeout (int): seconds before a process tree is killed forcefully, defaults to 3600\n - shell (bool): Shall we use the cmd.exe or /usr/bin/env shell for command execution, defaults to False\n - encoding (str/bool): Which text encoding the command produces, defaults to cp437 under Windows and utf-8 under Linux\n - stdin (sys.stdin/int): Optional stdin file descriptor, sent to the process command_runner spawns\n - stdout (str/queue.Queue/function/False/None): Optional path to filename where to dump stdout, or queue where to write stdout, or callback function which is called when stdout has output\n - stderr (str/queue.Queue/function/False/None): Optional path to filename where to dump stderr, or queue where to write stderr, or callback function which is called when stderr has output\n - no_close_queues (bool): Normally, command_runner sends None to stdout / stderr queues when process is finished. This behavior can be disabled allowing to reuse those queues for other functions wrapping command_runner\n - windows_no_window (bool): Shall a command create a console window (MS Windows only), defaults to False\n - live_output (bool): Print output to stdout while executing command, defaults to False\n - method (str): Accepts 'poller' or 'monitor' stdout capture and timeout monitoring methods\n - check interval (float): Defaults to 0.05 seconds, which is the time between stream readings and timeout checks\n - stop_on (function): Optional function that when returns True stops command_runner execution\n - on_exit (function): Optional function that gets executed when command_runner has finished (callback function)\n - process_callback (function): Optional function that will take command_runner spawned process as argument, in order to deal with process info outside of command_runner\n - split_streams (bool): Split stdout and stderr into two separate results\n - silent (bool): Allows to disable command_runner's internal logs, except for logging.DEBUG levels which for obvious reasons should never be silenced\n - priority (str): Allows to set CPU bound process priority (takes 'low', 'normal' or 'high' parameter)\n - io_priority (str): Allows to set IO priority for process (takes 'low', 'normal' or 'high' parameter)\n - heartbeat (int): Optional seconds on which command runner should log a heartbeat message\n - close_fds (bool): Like Popen, defaults to True on Linux and False on Windows\n - universal_newlines (bool): Like Popen, defaults to False\n - creation_flags (int): Like Popen, defaults to 0\n - bufsize (int): Like Popen, defaults to 16384. Line buffering (bufsize=1) is deprecated since Python 3.7\n\n**Note that ALL other subprocess.Popen arguments are supported, since they are directly passed to subprocess.**\n\n\n### command_runner Python 2.7 compatible queue reader\n\nThe following example is a Python 2.7 compatible threaded implementation that reads stdout / stderr queue in a thread.\nThis only exists for compatibility reasons.\n\n```python\nimport queue\nimport threading\nfrom command_runner import command_runner\n\ndef read_queue(output_queue):\n    \"\"\"\n    Read the queue as thread\n    Our problem here is that the thread can live forever if we don't check a global value, which is...well ugly\n    \"\"\"\n    stream_output = \"\"\n    read_queue = True\n    while read_queue:\n        try:\n            line = output_queue.get(timeout=1)\n        except queue.Empty:\n            pass\n        else:\n            # The queue reading can be stopped once 'None' is received.\n            if line is None:\n                read_queue = False\n            else:\n                stream_output += line\n                # ADD YOUR LIVE CODE HERE\n\n\n# Create a new queue that command_runner will fill up\noutput_queue = queue.Queue()\n\n# Create a thread of read_queue() in order to read the queue while command_runner executes the command\nread_thread = threading.Thread(\n    target=read_queue, args=(output_queue)\n)\nread_thread.daemon = True  # thread dies with the program\nread_thread.start()\n\n# Launch command_runner, which will be blocking. Your live code goes directly into the threaded function\nexit_code, output = command_runner('ping 127.0.0.1', stdout=output_queue, method='poller')\n```\n\n# UAC Elevation / sudo elevation\n\ncommand_runner package allowing privilege elevation.\nBecoming an admin is fairly easy with command_runner.elevate\nYou only have to import the elevate module, and then launch your main function with the elevate function.\n\n### elevation In a nutshell\n\n```python\nfrom command_runner.elevate import elevate\n\ndef main():\n    \"\"\"My main function that should be elevated\"\"\"\n    print(\"Who's the administrator, now ?\")\n\nif __name__ == '__main__':\n    elevate(main)\n```\n\nelevate function handles arguments (positional and keyword arguments).\n`elevate(main, arg, arg2, kw=somearg)` will call `main(arg, arg2, kw=somearg)`\n\n### Advanced elevate usage\n\n#### is_admin() function\n\nThe elevate module has a nifty is_admin() function that returns a boolean according to your current root/administrator privileges.\nUsage:\n\n```python\nfrom command_runner.elevate import is_admin\n\nprint('Am I an admin ? %s' % is_admin())\n```\n\n#### sudo elevation\n\nInitially designed for Windows UAC, command_runner.elevate can also elevate privileges on Linux, using the sudo command.\nThis is mainly designed for PyInstaller / Nuitka executables, as it's really not safe to allow automatic privilege elevation of a Python interpreter.\n\nExample for a binary in `/usr/local/bin/my_compiled_python_binary`\n\nYou'll have to allow this file to be run with sudo without a password prompt.\nThis can be achieved in `/etc/sudoers` file.\n\nExample for Redhat / Rocky Linux, where adding the following line will allow the elevation process to succeed without password:\n```\nsomeuser ALL= NOPASSWD:/usr/local/bin/my_compiled_python_binary\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnetinvent%2Fcommand_runner","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnetinvent%2Fcommand_runner","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnetinvent%2Fcommand_runner/lists"}