Shell Interaction in Python: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= * Python Code Examples =Organizatorium= <syntaxhighlight lang='python'> from shutil import which commands={ "aws":...")
 
 
(16 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Internal=
=Internal=
* [[Python Code Examples#Code_Examples|Python Code Examples]]
* [[Python Code Examples#Code_Examples|Python Code Examples]]
* [[Python_Module_shutil|shutil]]
=Command Line Argument Processing=
[[Python_Language_Modularization#Standalone_Program|Standalone Python programs]] often needs to handle command line arguments.
<code>[[Python_Module_sys#sys.argv|sys.argv]]</code> is the list containing arguments as strings.
The path of the script being executed is available on position 0.
<syntaxhighlight lang='python'>
import sys
print(f"Arguments count: {len(sys.argv)}")
for i, arg in enumerate(sys.argv):
  print(f"Argument {i:>1}: {arg}")
</syntaxhighlight>
<font color=darkkhaki>Also explore <code>[[Python_Package_argparse|argparse]]</code>.</font>
=Execute an O/S Command=
==Execute an O/S Command with the <tt>subprocess</tt> Module==
{{Internal|Python_Module_subprocess#Execute_an_O.2FS_Command|Execute an O/S Command with the <tt>subprocess</tt> Module}}
==Other Methods==
<font color=darkkhaki>TO PROCESS:
* https://janakiev.com/blog/python-shell-commands/
* https://amoffat.github.io/sh/
</font>


=Organizatorium=
=Organizatorium=
Line 13: Line 40:
for c in commands:
for c in commands:
   print("{:20}{:7}".format(commands[c], "OK" if which(c) else "missing"))
   print("{:20}{:7}".format(commands[c], "OK" if which(c) else "missing"))
'
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 02:06, 8 July 2022

Internal

Command Line Argument Processing

Standalone Python programs often needs to handle command line arguments.

sys.argv is the list containing arguments as strings.

The path of the script being executed is available on position 0.

import sys

print(f"Arguments count: {len(sys.argv)}")
for i, arg in enumerate(sys.argv):
  print(f"Argument {i:>1}: {arg}")

Also explore argparse.

Execute an O/S Command

Execute an O/S Command with the subprocess Module

Execute an O/S Command with the subprocess Module

Other Methods

TO PROCESS:

Organizatorium

from shutil import which

commands={
  "aws":                "awscli",
  "aws-login":          "aws-login",
  "aws-eks-configure":  "aws-eks-configure"
}
for c in commands:
  print("{:20}{:7}".format(commands[c], "OK" if which(c) else "missing"))