My code :
SITE27=`python2.7 -c "import site; print site.getsitepackages()"`
errInfo27="$?"
echo $SITE27
if [ $errInfo27 -eq 0 ]; then
case ${SITE27} in
*\ * ) echo "VAR=$VAR has at least one space char";
;;
* ) echo "VAR=$VAR has no space chars" ;;
esac
fi
Then for echo $SITE27, I get:
['/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/Library/Python/2.7/site-packages']
How do I just extract the last path which is /Library/Python/2.7/site-packages ?
Thank you very much.
LJ
SITE27=$(python2.7 -c "import site; print site.getsitepackages()[-1]")
Get last element of the list using [-1]: site.getsitepackages()[-1]
Related
Im writing a bash script that automates the usage of other python tests (imagedeploy, hydrationwiring). The bash script looks at a .txt list of device names, and then goes down the list and performs 2 things (imagedeploy,hydrationwiring) on each name in the .txt.
What happens is that hydrationwiring test will return a non zero return value at the end, which breaks the loop and ends the script.
I want the script to continue going down the list of p, regardless of non 0 returns, until each device in the list p has been touched.
My question: how can I make my while loop continue on regardless of non 0 returns.
#!/bin/bash
if [ -z "$1" ]
then
echo "Usage: "devices.txt""
exit 1
fi
FILENAME=$1
RESULTFILE="/home/user/ssim-results/RduLabTestResults"
date >> $RESULTFILE
while read p; do
echo "TESTING $p:"
LOGFILE="/home/user/ssim-results/RduLabTestLog_${p}.log"
SUMMARYFILE="/home/user/ssim-results/RduLabTestLog_${p}.summary"
#echo "STEP1: imagedeploy -d $p --latest-release4"
echo "STEP1: imagedeploy -d $p --latest-release4"
#imagedeploy -d $p --latest-release4
if [ $? -eq 0 ] #imagedeploy pass/failure condition
then
echo "STEP2: LLDP check"
#runtests.sh -l INFO --vx-img -i /home/frogs/vmlocker/cloud/vx/latest-vx-rel $TESTS_HOME/tests/platform/HydrationWiring.py -d $p -T $LOGFILE -r $SUMMARYFILE
runtests.sh -l INFO --vx-img -i $VXREL3 $TESTS_HOME/tests/platform/HydrationWiring.py -d $p -T $LOGFILE -r $SUMMARYFILE
echo "STEP3: checking result"
if grep --quiet success $SUMMARYFILE
then
echo "$p PASS" >> $RESULTFILE
else
echo "$p FAIL" >> $RESULTFILE
fi
else
echo "imagedeploy failed"
fi
done <$FILENAME
ImageDeploy is commented out because imagedeploy works as intended. The issue is in "step 2". The runtest.sh hydrationwiring
output:
FAILED (errors=1)
STEP3: checking result
It only tested the first device on my list because it failed, I would like the output to be something like this:
FAILED (errors=1)
STEP3: checking result
next device...
PASS
STEP3: checking result
next device...
FAILED (error=1)
STEP3: checking result
next device...
Passed
STEP3: checking result
etc
I'm beginning with bash and I'm executing a script :
$ ./readtext.sh ./InputFiles/applications.txt
Here is my readtext.sh code :
#!/bin/bash
filename="$1"
counter=1
while IFS=: true; do
line=''
read -r line
if [ -z "$line" ]; then
break
fi
echo "$line"
python3 ./download.py \
-c ./credentials.json \
--blobs \
"$line"
done < "$filename"
I want to print the string ("./InputFiles/applications.txt") in a python file, I used sys.argv[1] but this line gives me -c. How can I get this string ? Thank you
It is easier for you to pass the parameter "$1" to the internal command python3.
If you don't want to do that, you can still get the external command line parameter with the trick of /proc, for example:
$ cat parent.sh
#!/usr/bin/bash
python3 child.py
$ cat child.py
import os
ext = os.popen("cat /proc/" + str(os.getppid()) + "/cmdline").read()
print(ext.split('\0')[2:-1])
$ ./parent.sh aaaa bbbb
['aaaa', 'bbbb']
Note:
the shebang line in parent.sh is important, or you should execute ./parent.sh with bash, else you will get no command line param in ps or /proc/$PPID/cmdline.
For the reason of [2:-1]: ext.split('\0') = ['bash', './parent.sh', 'aaaa', 'bbbb', ''], real parameter of ./parent.sh begins at 2, ends at -1.
Update: Thanks to the command of #cdarke that "/proc is not portable", I am not sure if this way of getting command line works more portable:
$ cat child.py
import os
ext = os.popen("ps " + str(os.getppid()) + " | awk ' { out = \"\"; for(i = 6; i <= NF; i++) out = out$i\" \" } END { print out } ' ").read()
print(ext.split(" ")[1 : -1])
which still have the same output.
This is the python file that you can use in ur case
import sys
file_name = sys.argv[1]
with open(file_name,"r") as f:
data = f.read().split("\n")
print("\n".join(data))
How to use sys.argv
How to use join method inside my python code
Can anyone guide me? I'm trying to migrate a kshell script to python.
If anyone could guide me on how to proceed on this task. Do I really need the function? I'm trying to make more concise easy to read. Thank you.
here is the code:
#!/bin/ksh
DB="BATCH_JOB_STAT"
LINE=$DB
export $DB
NoFile()
{
# no file
COLOR="clear"
LINE=$DB" NO BATCH_JOB ERROR FLAG FOUND"
echo $LINE
$BB $BBDISP "status ${MACHINE}.BATCH_JOB_STAT $COLOR `date` $LINE"
exit 1
}
MultiFile()
{
fail_flag=0
# Check more than One file
files=$(ls /opt/rh/flag/*)
for file in $files
do
if [ -f $file ] ; then
## echo "# Error. Flag File found: $file"
fail_flag=1
fi
done
## echo "-- Fail flag is : $fail_flag"
if [ $fail_flag -eq 0 ]; then
# no FAIL status means GOOD
COLOR="green"
LINE=$DB" OK"
echo $LINE
else
COLOR="red"
LINE=$DB" BATCH_JOB ERROR FLAG FILE FOUND. <P> -- $file -- </P> <P> Support <A HREF=http://johndoe/support.htm> Tech </A>"
echo $LINE
fi
$BB $BBDISP "status ${MACHINE}.BATCH_JOB_STAT $COLOR `date` $LINE"
}
# MAIN
file_count=$(ls -l /opt/rh/flag 2>/dev/null |grep -v total |wc -l)
case "$file_count" in
0) NoFile ;;
*) MultiFile ;;
esac
exit 0
I suggest you to see shutil for high-level operations on files in Python. And of course, sys and os (which are used by the first).
I'd like to browse a terminal dialog menu with the arrow keys (like bash 'dialog')
I would prefer ruby solution, but bash/python could work.
read -n1 input # is not good enough, cause the arrow keys are not regular chars.
Also, the 'read' in mac term doesn't support smaller timeout than 1 second.
Anything?
Thanks,
I am not sure what you are looking for -
a way to simulate key presses to an application, or
a way to generate simple dialog boxes, or
a way to read characters from a keyboard...
However, these may give you some ideas:
For 1: You would probably need to look at the Automator and Applescript
tell application "System Events" to tell process "Finder"
click menu item "New Finder Window" of menu 1 of menu bar item "File" of menu bar 1
end tell
For 2: You could look at Platypus for generating dialog boxes and wrappers around scripts - available here
For 3: The following may do something like you want
#!/bin/bash
#
# Read a key in cbreak mode
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
#
# If ESCAPE, read next part
if [ $KEY = $'' ]; then
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
[ $KEY = "A" ] && echo UP
[ $KEY = 'B' ] && echo DOWN
[ $KEY = 'C' ] && echo RIGHT
[ $KEY = 'D' ] && echo LEFT
exit
fi
echo $KEY
I should explain that the if [ $KEY line needs to be typed
if [ $KEY = $'CONTROL-V ESCAPE' ]
i.e. type these 5 things
$
single quote
Control V
Escape
single quote
According to Mark Setchell, minor modification:
#!/bin/bash
# Read a key in cbreak mode
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
# Check if it's a single alphanumeric char
if $(echo $KEY | grep -q -e "[a-zA-Z0-9]"); then
echo $KEY
exit
# Else we assume escape char (doesn't cover all cases)
else
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
[ $KEY == 'A' ] && echo UP
[ $KEY == 'B' ] && echo DOWN
[ $KEY == 'C' ] && echo RIGHT
[ $KEY == 'D' ] && echo LEFT
exit
fi
I have two scripts:
Python:
if canceled==True:
os.environ["c"] = "0"
if canceled==False:
os.environ["c"] = "1"
Bash:
kill_jobs()
{
pkill -TERM -P "$BASHPID"
echo $c
if [ $c == "0" ]
then
echo -e "OPERATIONS CANCELED"
elif [ $c == "1" ]
then
echo -e "OPERATIONS FINISHED"
fi
}
trap kill_jobs EXIT
How can I do to pass a python variable to bash script ?
(My level in bash is near to 0 ...)
Thanks
Edit: Now I have this error: (in french)
[: == : opérateur unaire attendu
Or you can try:
os.environ["c"] = "value"
You can set it this way, I guess
Refer
The python script should end with:
print c
Then you use it in bash with:
c=$(python_script)