meta data for this page
  •  

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
programming:python:run_system_command [2024/02/10 09:36] – created niziakprogramming:python:run_system_command [2024/02/23 08:46] (current) niziak
Line 1: Line 1:
 +====== system / popen / exec ======
  
 +In general: run system commands.
 +
 +Current recommended way is to use [[https://docs.python.org/3/library/subprocess.html|subprocess]] module. This module intends to **replace several older** modules and functions:
 +<code python>
 +os.system
 +os.spawn*
 +</code>
 +
 +[[https://docs.python.org/3/library/subprocess.html#replacing-older-functions-with-the-subprocess-module|Replacing Older Functions with the subprocess Module]]
 +
 +[[https://docs.python.org/3/library/subprocess.html#replacing-os-system|Replacing os.system()]]
 +
 +Features:
 +  * possible to execute in shell:
 +    * all command and params can be specified as string not list
 +    * multiple commands can be executed at once; shell pipes usage possible
 +  * configurable check for return codes or output
 +
 +Parameters:
 +  * [[https://docs.python.org/3.10/library/io.html#io-text-encoding|io-text-encoding]]
 +  * 
 +
 +Examples:
  
 <code python> <code python>
Line 6: Line 30:
     return output.communicate()[0].decode("utf-8").split("\n")     return output.communicate()[0].decode("utf-8").split("\n")
 </code>     </code>    
 +
 +see [[programming:python:lib:contextlib]] to catch other components stdout/stderr.
 +
 +<code python>
 +import subprocess
 +meta_data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles'])
 +data = meta_data.decode('utf-8', errors ="backslashreplace")
 +</code>
 +
 +<code python>
 +return subprocess.check_output(
 +                [self.FW_PRINTENV, '-n', var],
 +                stderr=subprocess.STDOUT, encoding='ascii').strip()
 +...                
 +return subprocess.check_call([self.FW_SETENV, var, value])                
 +</code>
 +