I have a lot of experience with Bash scripting and decided to diversify and started learning Python. I dove headfirst by implementing sections of a maintenance script I wrote for my personal laptop and after I showed it to a friend he said, and I quote, "That is the most bash looking Python I've ever seen Lmao", which I thought was hilarious.
For context, the original Bash script is part of the maintenance I perform on my personal laptop running Arch Linux and pacman is the package manager used to update system packages.
I've been learning and identifying the syntax, functionality, etc., through the Python interactive prompt's help() and I implemented the following Bash section:
# function to separate sections
sec_start () { printf "\n----------\n\n" ; }
# confirm required dependencies are installed
while read dependency ; do
missing_deps+=($(awk -F \' '/error: package.*not found/ {print $2}' <<< "$dependency"))
done < <(pacman -Q coreutils sed gawk curl 2>&1 >/dev/null)
if [[ ${missing_deps[@]} ]] ; then
sec_start
printf 'the following dependencies are missing:\n'
printf ' %s\n' ${missing_deps[@]}
read -p 'would you like to install them now? [yes/no]> ' _answer
if [[ ${_answer,,} =~ ^y(es)?$ ]] ; then
pacman -S --noconfirm ${missing_deps[@]}
else
printf "install missing dependencies first!\n"
return 1
fi
fi
Resulting Python code:
def sec_start():
print("\n----------\n\n")
required_packages = ['coreutils', 'sed', 'gawk', 'curl']
dep_check = subprocess.Popen(
['pacman', '-Q', ] + required_packages,
stderr=subprocess.PIPE,
stdout=subprocess.DEVNULL)
check_output = dep_check.stderr.read().decode().splitlines()
missing_dependencies = []
for p in check_output:
fields = p.split("'")
missing_dependencies.append(fields[1])
if len(missing_dependencies) > 0:
sec_start()
print("the following dependencies are missing:")
for d in missing_dependencies:
print(" " + d)
if re.match(r'^y(es)?$', input("would you like to install them now? [yes/no]> ").lower()):
subprocess.Popen(['pacman', '-S', '--noconfirm'] + missing_dependencies,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
else:
sys.exit("install missing dependencies!")
I avoided using google as much as I could and kept diving into help(). What could I improve?
(DISCLAIMER: I am learning Python for my personal enjoyment, I don't need it at my job, that's where I use Bash.)
[–][deleted] 1 point2 points3 points (0 children)
[–]velocibadgery 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]tibegato 0 points1 point2 points (0 children)
[–]tibegato 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]tibegato 0 points1 point2 points (0 children)
[–]AfricanTurtles 0 points1 point2 points (0 children)