Package: detachedproc
Similar to subprocess, but with 100% detached processesTested against Windows 10 / Python 3.11 / Anaconda and Ubuntupip install detachedprocThe module defines a Python class named DetachedPopen that enable the execution and management
of detached processes, primarily on Windows but with some compatibility for Unix-like systems as well.Here's an overview of what the module does:Detached Process Execution:The main purpose of the module is to execute external processes in a detached manner,
meaning the processes run independently of the Python script,
and the script can continue its execution without waiting for the process to finish.Windows Compatibility:The module provides options for running processes with various Windows-specific features,
such as specifying window styles ("Normal," "Hidden," "Minimized," "Maximized")
and verbs (used in shell execution).Input and Output Handling:It allows you to specify the standard input of the process and capture its standard output and standard error.
You can print or capture the output as needed.
Additionally, it supports buffering for both standard output and standard error.Process Monitoring:The module uses the psutil library to monitor and manage processes.
It can track child processes spawned by the executed command.Temporary File Management:Temporary files are created for various purposes (e.g., passing input, capturing output)
during process execution. You have the option to delete these temporary files when they are no longer needed.Compatibility with subprocess:The module is designed with some compatibility with the subprocess.Popen class,
allowing users familiar with the standard library subprocess module to transition to
this more specialized functionality while maintaining a similar interface.Advantages:Detached Execution:This module is particularly useful when you need to run external commands or processes that might take a long time to complete, and you want your Python script to continue executing other tasks without waiting for the external process.Windows Integration:It offers features specifically tailored for Windows users, such as controlling window styles and verbs when executing processes.Input and Output Handling:It provides flexibility in handling process input and capturing output, which can be essential when dealing with command-line tools and automation.# Important! "powershell.exe -ExecutionPolicy RemoteSigned Start-Process ..." is used to execute the subprocess, you might need to allow that.importsubprocessfromtimeimportsleepfromdetachedprocimportDetachedPopenp=DetachedPopen(args=[rf"ping.exe",'-n','10000',"8.8.8.8"],bufsize=-1,executable=None,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE,preexec_fn=None,close_fds=True,shell=False,cwd=None,env=None,universal_newlines=None,startupinfo=None,creationflags=0,restore_signals=True,start_new_session=False,pass_fds=(),user=None,group=None,extra_groups=None,encoding=None,errors=None,text=None,umask=-1,pipesize=-1,window_style="Hidden",wait=False,verb=None,what_if=False,print_stdout=False,print_stderr=False,capture_stdout=True,capture_stderr=True,stdoutbuffer=None,stderrbuffer=None,psutil_timeout=15,delete_tempfiles=True,read_stdout_stderr_async=False,args_to_83=True,)whileTrue:print(p.stdout.read())sleep(1)Aclassforlaunchingandmanagingdetachedprocesses.Thisclassprovidesawaytoexecuteprocessesinthebackground,similartothe`subprocess.Popen`class.Itallowsyoutorunprocesseswithvariousoptionsandprovidesmethodsforcontrollingandmonitoringthem.Args:args(listorstr):Thecommandtobeexecutedasalistofargumentsorasinglestringtobeparsed.bufsize(int):Notused;includedforcompatibilitywith`subprocess.Popen`.executable(str):Notused;includedforcompatibilitywith`subprocess.Popen`.stdin(strorNone):Inputtobeprovidedtotheprocess's standard input. Default is None.stdout(Noneorsubprocess.PIPE):Thestandardoutputoftheprocess.DefaultisNone.stderr(Noneorsubprocess.PIPE):Thestandarderroroftheprocess.DefaultisNone.preexec_fn(callableorNone):Notused;includedforcompatibilitywith`subprocess.Popen`.close_fds(bool):Notused;includedforcompatibilitywith`subprocess.Popen`.shell(bool):Notused;includedforcompatibilitywith`subprocess.Popen`.cwd(strorNone):Theworkingdirectoryfortheprocess.DefaultisNone.env(dictorNone):Theenvironmentvariablestobeusedfortheprocess.DefaultisNone.universal_newlines(boolorNone):Notused;includedforcompatibilitywith`subprocess.Popen`.startupinfo(subprocess.STARTUPINFO):Notused;includedforcompatibilitywith`subprocess.Popen`.creationflags(int):Notused;includedforcompatibilitywith`subprocess.Popen`.restore_signals(bool):Notused;includedforcompatibilitywith`subprocess.Popen`.start_new_session(bool):Notused;includedforcompatibilitywith`subprocess.Popen`.pass_fds(tuple):Notused;includedforcompatibilitywith`subprocess.Popen`.user(strorNone):Notused;includedforcompatibilitywith`subprocess.Popen`.group(strorNone):Notused;includedforcompatibilitywith`subprocess.Popen`.extra_groups(listorNone):Notused;includedforcompatibilitywith`subprocess.Popen`.encoding(strorNone):Notused;includedforcompatibilitywith`subprocess.Popen`.errors(strorNone):Notused;includedforcompatibilitywith`subprocess.Popen`.text(boolorNone):Notused;includedforcompatibilitywith`subprocess.Popen`.umask(int):Notused;includedforcompatibilitywith`subprocess.Popen`.pipesize(int):Notused;includedforcompatibilitywith`subprocess.Popen`.wait(bool):Whethertowaitfortheprocesstocompletebeforereturning.DefaultisFalse.verb(strorNone):Theverbtousewhenexecutingtheprocess(Windowsonly).DefaultisNone.what_if(bool):Whethertosimulatetheexecutionoftheprocesswithoutactuallyrunningit(Windowsonly).DefaultisFalse.window_style(str):Thewindowstylefortheprocess(Windowsonly).Possiblevalues:"Normal","Hidden","Minimized","Maximized".Defaultis"Normal".print_stdout(bool):Whethertoprinttheprocess's standard output. Default is True.print_stderr(bool):Whethertoprinttheprocess's standard error. Default is True.capture_stdout(bool):Whethertocapturetheprocess's standard output. Default is True.capture_stderr(bool):Whethertocapturetheprocess's standard error. Default is True.stdoutbuffer(intorNone):Themaximumnumberoflinestobufferforstandardoutput.DefaultisNone.stderrbuffer(intorNone):Themaximumnumberoflinestobufferforstandarderror.DefaultisNone.psutil_timeout(int):Themaximumtimetowaitforprocessinformationusingpsutil.Defaultis15seconds.delete_tempfiles(bool):Whethertodeletetemporaryfilescreatedduringexecution.DefaultisTrue.read_stdout_stderr_async(bool):Whethertoreadstdout/stderrduringexecution(Truemeansslowerexecution).DefaultisFalseargs_to_83(bool):Whethertoconvertargumentsto8.3format(Windowsonly)-Themainexecutablewillalwaysbeconvertedto8.3format,thisisonlyfortheargumentsafterwards(args[1:]).DefaultisTrue.Methods:terminate():Terminatetheprocess.kill():Terminatetheprocess.send_signal():Terminatetheprocess.Toreadstandardoutput:stdout.read():Readtheprocess's standard output.stdout.readlines():Readtheprocess's standard output as a list of lines.stdout.readline():Readasinglelinefromtheprocess's standard output.Toreadstandarderror:stderr.read():Readtheprocess's standard error.stderr.readlines():Readtheprocess's standard error as a list of lines.stderr.readline():Readasinglelinefromtheprocess's standard error.TouseitonUbuntu# Update the list of packagessudoapt-getupdate# Install pre-requisite packages.sudoapt-getinstall-ywgetapt-transport-httpssoftware-properties-common# Download the Microsoft repository GPG keyswget-q"https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb"# Register the Microsoft repository GPG keyssudodpkg-ipackages-microsoft-prod.deb# Delete the the Microsoft repository GPG keys filermpackages-microsoft-prod.deb# Update the list of packages after we added packages.microsoft.comsudoapt-getupdate# Install PowerShellsudoapt-getinstall-ypowershell# Start PowerShellpwsh# As superuser, register the Microsoft repository once. After registration, you can update PowerShell withsudoapt-getinstallpowershell.