How to use terminal input as Python argument? - python

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

Related

Get a string in Shell/Python using sys.argv

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

How to get shellscript filename without $0?

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

How to pass an array from python to shell script and execute it?

I have an array HSPACE which is defined inside a python script. I am trying to pass this array to a shell script "arraytest" and execute it from python itself. I am trying with the following piece of code but it doesnt seem to be working:
HSPACE=[0.01, 0.009, 0.008, 0.007]
subprocess.call(["./arraytest"], HSPACE, shell=True)
The content of the shell script is:
#!/bin/bash
for i in ${HSPACE[#]}
do
echo $i
done
The easy answer is to pass each array entry as a literal argv entry:
subprocess.call(['./arraytest'] + [str(s) for s in HSPACE], shell=False)
...thereafter...
#!/bin/bash
printf 'hspace array entry: %q\n' "$#"
Another approach is to pass an array as a NUL-delimited stream on stdin:
p = subprocess.Popen(['./arraytest'], shell=False, stdin=subprocess.PIPE)
p.communicate('\0'.join(str(n) for n in HSPACE) + '\0')
...and, in your shell:
#!/bin/bash
arr=( )
while IFS= read -r -d '' entry; do
arr+=( "$entry" )
done
printf 'hspace array entry: %q\n' "${arr[#]}"

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

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