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/09 12:19] – [Beispiel] msuter | modul:m122:learningunits:lu08:module [2024/12/16 08:51] (aktuell) – [Beispiel] msuter | ||
---|---|---|---|
Zeile 46: | 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 61: | 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(" | ||
</ | </ | ||