Writing Python Conditionals For Crontab
Solution 1:
A much better solution is to avoid a subprocess entirely. (And even if you use a subprocess, don't use ls
in scripts.)
from pathlib import Path
dotfiles = Path().glob('.[!.]*')
iflen(list(dotfiles)) > 0:
do_things()
Actually, there is no real need to check the length; you can say
dotfiles = list(Path().glob('.[!.]*'))
if dotfiles:
do_things('The files which matched are %s' % dotfiles)
Somewhat obscurely, but more succinctly, you could iterate over the generator instead; the loop body will be executed only if there is at least one file which matches. This is an optimization if you only care whether there is at least one file, as it stops once it finds the first one;
for file in Path().glob('.[!.]*'):
do_things()
break
Python doesn't care whether you run your script from cron
or not (though sometimes you need to arrange the environment for Python in your cron
job if you have libraries installed in nonstandard locations). But why are you using Python at all here if all your business logic is in shell scripts? (Though your shell scripting could also benefit from studying some antipatterns to avoid.)
Here's the whole thing entirely in shell script, using similar logic:
for file in .[!.]*; dotest -e "$file" || break# cf nullgbob
executeAlert.sh
breakdone
Bash offers shopt -s nullglob
to avoid entering the loop if the wildcard has no match; but cron
runs sh
and it's not altogether hard to avoid bashisms here (though the globbing behavior in the case of no matches is surprising).
If you want all the matches in a shell script, you can say
set -- .[!.]*
if [ "$@" != ".[!.]*" ]; then
executeAlert.sh "$@"# argument is list of matching filesfi
If you use Bash or ksh, you could collect the matches into an array;
shopt -s nullglob
dotfiles=(.[!.]*)
for file in"${dotfiles[@]}"; doecho"Here's one dotfile: $file"doneif [[ "${#dotfiles[@]}" > 0 ]]; then
executeAlert.sh "${dotfiles[@]}"fi
Your egrep
regex would only match on dot directories; I have assumed that this was a mistake.
Solution 2:
printing res.stdout
will show you that it has an endline character within it.
>>>res.stdout'0\n'
so just strip the '\n' character:
res = res.stdout.strip('\n')
ifres== "0":
(executeAlert.sh script)
Alternatively, just cast it as an integer:
ifint(res.stdout)== 0:
(executeAlert.sh script)
Post a Comment for "Writing Python Conditionals For Crontab"