Subprocess Library Won't Execute Compgen

subprocess.run() doesn't return any output

When you run a program specifying shell=True, the command argument can be a single string instead of a list of strings. This is one instance where it needs to be a single string:

import subprocess

bash_command = 'compgen -c' # single string
process = subprocess.run(bash_command,
check=True,
text=True,
shell=True,
executable='/bin/bash',
capture_output=True
)

software_list = process.stdout.split('\n')
print(software_list)

Run BASH built-in commands in Python?

I finally found a solution that works.

from subprocess import Popen, PIPE, STDOUT
shell_command = 'bash -i -c "history -r; history"'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE,
stderr=STDOUT)

output = event.communicate()

Thank you everyone for the input.

Why won't my function execute

You have a typo in this line totalRatio = sumCount/floar(length)*100. You need float instead of floar.

Secondly, you have loads of missing parenthesis in almost all lines with the print function.

If you want the function to return value, you should use return instead of print's:

return (str(product)
+ ": product after multiplying the birth year to itself.\n"
+ str(onesCount)
+ ": number of ones found at a rate of " + str(oneRation) + "percent.\n"
+ str(threeCount)
+ ": number of threes found at a rate of " + str(threeRatio) + "percent\n"
+ str(fiveCount)
+ ": number of fives found at a rate of " + str(fiveRatio) + "percent\n"
+ str(sevenCount)
+ ": number of sevens found at a rate of " + str(sevenRatio) + "percent\n"
+ str(nineCount)
+ ": number of nine found at a rate of " + str(nineRatio) + "percent\n"
+ str(sumCount)
+ ": total odd numbers found at a rate of " + str(totalRatio) + "percent\n")

Test whether a glob has any matches in Bash

Bash-specific solution:

compgen -G "<glob-pattern>"

Escape the pattern or it'll get pre-expanded into matches.

Exit status is:

  • 1 for no-match,
  • 0 for 'one or more matches'

stdout is a list of files matching the glob.
I think this is the best option in terms of conciseness and minimizing potential side effects.

Example:

if compgen -G "/tmp/someFiles*" > /dev/null; then
echo "Some files exist."
fi


Related Topics



Leave a reply



Submit