How to get shellscript filename without $0? - python

I tried to use python practice if __name__ == "__main__": on shellscript.
Sample scripts are the following:
a.sh:
#!/bin/bash
filename="a.sh"
function main() {
echo "start from $0"
echo "a.sh is called"
source b.sh
bfunc
}
[[ "$0" == "${filename}" ]] && main
b.sh:
#!/bin/bash
filename="b.sh"
function main() {
echo "start from $0"
echo "b.sh is called"
}
function bfunc() {
echo "hello bfunc"
}
[[ "$0" == "${filename}" ]] && main
You can call it with bash a.sh.
If you call bash a.sh, you'll get like the following:
start from a.sh
a.sh is called
hello bfunc
Here is my question.
How can I get file name itself without using $0?
I don't want to write file name directly, i.e. I want to pass the file name value to ${filename}.
See the link if you don't know that is the above python practice: What does if __name__ == "__main__": do?
How can I check wheather b.sh is started from command line or was executed by including from a.sh?

You may use the variable $BASH_SOURCE to get the name of the current script file.
if [[ "$0" == "$BASH_SOURCE" ]]
then
: "Execute only if started from current script"
else
: "Execute when included in another script"
fi

Related

How to use terminal input as Python argument?

I am writing a Python script that is started by a .sh file and accepts 2-3 parameters. I have written what I want in Java, but I'm not sure how to put in bash.
Scanner i = new Scanner(System.in);
String f, f1, f2;
System.out.print("Enter type: ");
f = i.next();
if (f.equals("a")){
System.out.print("Enter var1");
f1 = i.next();
// run "python script.py a [f1]"
}
else if (f.equals("b")){
System.out.print("Enter var1");
f1 = i.next();
System.out.print("Enter var2");
f2 = i.next();
// run "python script.py b [f1] [f2]"
}
This is what I have so far:
a="e"
b="test.txt"
c=""
python main.py "$a" "$b" "$c"
I've looked at How to concatenate string variables in Bash, but I'm not sure how to put it in a conditional statement.
How do I put the read-ins in conditional statements in bash?
Here's a starter Bash script:
echo "Enter type"
read f
if [ "$f" = "a" ]; then
echo "Enter var1"
read f1
if [ -z "$f1" ]; then
# -z means "variable is empty", i.e. user only pressed Enter
python script.py "$f"
else
python script.py "$f" "$f1"
fi
fi

How to access python return value from bash script

I'm trying to understand how to access from a bash script the return value of a python script.
Clarifying through an example:
foo.py
def main():
print ("exec main..")
return "execution ok"
if __name__ == '__main__':
main()
start.sh
script_output=$(python foo.py 2>&1)
echo $script_output
If I run the bash script, this prints the message "exec main..".
How can I store in script_output the return value (execution ok)?
If I direct execution ok to stdout, the script_output will capture all the stdout (so the 2 print statement).
Is there any way to implement this?
Thanks!
Alessio
Add a proper exit code from your script using the sys.exit() module. Usually commands return 0 on successful completion of a script.
import sys
def main():
print ("exec main..")
sys.exit(0)
and capture it in shell script with a simple conditional. Though the exit code is 0 by default and need not be passed explicitly, using sys.exit() gives control to return non-zero codes on error cases wherever applicable to understand some inconsistencies with the script.
if python foo.py 2>&1 >/dev/null; then
echo 'script ran fine'
fi
You can get the previous command's output status through $?. If the python script ran successfully without any stderr, it should return 0 as exit code else it would return 1 or any number other than 0.
#!/bin/bash
python foo.py 2>&1 /dev/null
script_output=$?
echo $script_output
Bash contains only return code in $?, so you can't use it to print the text from python's return.
My solution is write in to the stderr in python script, next print only stderr in bash:
import sys
def main():
print ("exec main..")
sys.stderr.write('execution ok\n')
return "execution ok"
if __name__ == '__main__':
main()
Bash:
#!/bin/bash
script_output=$(python foo.py 1>/dev/null)
echo $script_output
Output:
execution ok

return value from python script to shell script

I am new in Python. I am creating a Python script that returns a string "hello world." And I am creating a shell script. I am adding a call from the shell to a Python script.
i need to pass arguments from the shell to Python.
i need to print the value returned from Python in the shell script.
This is my code:
shellscript1.sh
#!/bin/bash
# script for testing
clear
echo "............script started............"
sleep 1
python python/pythonScript1.py
exit
pythonScript1.py
#!/usr/bin/python
import sys
print "Starting python script!"
try:
sys.exit('helloWorld1')
except:
sys.exit('helloWorld2')
You can't return message as exit code, only numbers. In bash it can accessible via $?. Also you can use sys.argv to access code parameters:
import sys
if sys.argv[1]=='hi':
print 'Salaam'
sys.exit(0)
in shell:
#!/bin/bash
# script for tesing
clear
echo "............script started............"
sleep 1
result=`python python/pythonScript1.py "hi"`
if [ "$result" == "Salaam" ]; then
echo "script return correct response"
fi
Pass command line arguments to shell script to Python like this:
python script.py $1 $2 $3
Print the return code like this:
echo $?
You can also use exit() without sys; one less thing to import. Here's an example:
$ python
>>> exit(1)
$ echo $?
1
$ python
>>> exit(0)
$ echo $?
0

python os.environ variable do not pass in the bash script

I have a python script (using a pseudo-terminal) to pass an environment variable called "CDP":
def download(self, dPluzz, donnees=None): # to call the bash script
self.child_pid = self.v.fork_command(None, ['/bin/bash', 'dPluzz-cli', '-f', dest, '-u', adresse])
os.environ["CDP"] = "False" # set cancel as "False"
def cancel(self, dPluzz, donnees=None):
if self.annul == 0:
if self.time > 10 and self.percent != 100:
os.environ["CDP"] = "True"
print os.environ["CDP"] # returns True
self.child_pid = str(self.child_pid)
cmd = 'kill -TERM' + " " + self.child_pid
subprocess.Popen(cmd, shell=True)
def __init__(self): #Pseudo-Terminal in GTK window
self.v = vte.Terminal() #(displayed in a notebook)
self.v.connect ("child-exited", lambda term: self.verif(self, a))
self.v.connect('contents-changed', self.term)
self.v.set_size(70,20)
self.v.set_encoding("UTF-8")
self.v.set_cursor_blinks(False)
self.v.show()
self.page.add(self.v)
The bash script is:
kill_jobs()
{
pkill -TERM -P "$BASHPID"
echo -e "$CDP" # returns False, should be True
if [ "$CDP" == "True" ]; then
echo -e "OPERATIONS ANNULEES"
elif [ "$CDP" == "False" ]; then
echo -e "OPERATIONS TERMINEES"
fi
}
The problem is, $CDP = False so the message displayed is not good.
What is the reason?
Thanks
After setting the environment via
os.environ["CDP"] = "True"
You can get this value in you bash only if you call the bash script via os.system(), os.popen() or os.fork() and os.execv().
so If you can add
os.system('/bin/bash script.sh')
You shall be able to use the value of CDP in bash script normally.
Please read os.putenv()
I guess os.environ and os.putenv() are closely related.

how to import python variable to bash

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)

Categories

Resources