Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
| Beide Seiten der vorigen Revision Vorhergehende Überarbeitung Nächste Überarbeitung | Vorhergehende Überarbeitung | ||
| modul:m122:learningunits:lu08:module [2024/12/02 09:18] – msuter | modul:m122:learningunits:lu08:module [2024/12/16 08:51] (aktuell) – [Beispiel] msuter | ||
|---|---|---|---|
| Zeile 12: | Zeile 12: | ||
| import subprocess | import subprocess | ||
| - | # Einen Bash-Befehl ausführen | + | bash_command = 'cat / | 
| - | result = subprocess.run([' | + | # Den Bash-Befehl ausführen | 
| + | try: | ||
| + |      | ||
| + | bash_command, | ||
| + | shell=True, # Use a shell to interpret the command | ||
| + |         check=True,  | ||
| + |          | ||
| + |         stdout=subprocess.PIPE,  | ||
| + |         stderr=subprocess.PIPE  | ||
| + | ) | ||
| + | return result | ||
| + | except subprocess.CalledProcessError as e: | ||
| + |     print(f' | ||
| + |     print(f' | ||
| + | sys.exit(1) | ||
| + | except Exception as ex: | ||
| + |     print(f' | ||
| + | sys.exit(1) | ||
| # Ausgabe anzeigen | # Ausgabe anzeigen | ||
| Zeile 29: | Zeile 46: | ||
| <code python> | <code python> | ||
| import os | import os | ||
| + | import sys | ||
| - | # Einen Bash-Befehl  | + | def run_bash_command(command): | 
| - | os.system(' | + |     """ | 
| + |     Führt einen Bash-Befehl  | ||
| + | |||
| + | :param command: Der auszuführende Bash-Befehl als String | ||
| + |     """ | ||
| + | try: | ||
| + |         print(f' | ||
| + |         # os.system  | ||
| + | exit_status = os.system(command) | ||
| + | |||
| + | if exit_status != 0: | ||
| + |             print(f'Fehler: Der Befehl ' | ||
| + | sys.exit(exit_status) | ||
| + | else: | ||
| + |             print(' | ||
| + | |||
| + | except Exception as e: | ||
| + |         print(f' | ||
| + | sys.exit(1) | ||
| + | |||
| + | bash_command = 'ls -l / | ||
| + | run_bash_command(bash_command) | ||
| </ | </ | ||
| Zeile 44: | Zeile 83: | ||
| <code python> | <code python> | ||
| import sh | import sh | ||
| + | import sys | ||
| + | |||
| + | def run_bash_command(command): | ||
| + |     """ | ||
| + | Führt einen Bash-Befehl aus und behandelt Fehler. | ||
| + | |||
| + | :param command: Der auszuführende Bash-Befehl als String | ||
| + |     """ | ||
| + | try: | ||
| + |         print(f" | ||
| + | # sh führt den Befehl aus und fängt automatisch Fehler ab | ||
| + |         result = sh.Command(command.split()[0])(*command.split()[1: | ||
| + | print(result) | ||
| + | |||
| + | except sh.ErrorReturnCode as e: | ||
| + |         print(f' | ||
| + | sys.exit(e.exit_code) | ||
| + | |||
| + | except Exception as e: | ||
| + |         print(f' | ||
| + | sys.exit(1) | ||
| + | |||
| + | # Beispielbefehl | ||
| + | bash_command = 'ls -l / | ||
| + | run_bash_command(bash_command) | ||
| - | # Bash-Befehl ausführen | ||
| - | print(sh.ls(" | ||
| </ | </ | ||