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)
Related
I have a setup.py file, which looks like this:
#!/usr/bin/env python
DIR = Path(__file__).parent
README = (DIR / "README.md").read_text()
install_reqs = parse_requirements(DIR / "requirements.txt")
try:
dev_reqs = parse_requirements(DIR / "requirements-dev.txt")
except FileNotFoundError:
dev_reqs = {}
print("INFO: Could not find dev and/or prepro requirements txt file.")
if __name__ == "__main__":
setup(
keywords=[
"demo"
],
python_requires=">=3.7",
install_requires=install_reqs,
extras_require={"dev": dev_reqs},
entry_points={
"console_scripts": ["main=smamesdemo.run.main:main"]
},
)
I want find this file recursively in a folder and extract the following part:
entry_points={
"console_scripts": ["main=smamesdemo.run.main:main"]
},
which may also look like this
entry_points={"console_scripts": ["main=smamesdemo.run.main:main"]}
DESIRED: I want to check if that entrypoints dictionary contains a console_scripts part which a script that starts with the name main and return a True or False (or throw an error).
I get find the file and the needed values like this:
grep -rnw "./" -e "entry_points"
This returns the following:
./setup.py:22: entry_points={
Does anyone know how to solve this?
Assuming that there's only one entry_points={...} block in the setup.py file with the same syntax you have stated in your example.
The following script will find the setup.py file in the current directory by providing the requested outputs.
#!/bin/bash
directory_to_find='.' # Directory path to find the "${py_script}" file.
py_script="setup.py" # Python script file name.
dictionary_to_match="console_scripts" # Dictionary to match
dictionary_script_to_match="main" # Script name to match - If the Dictionary found.
########################################################
py_script=$(find "${directory_to_find}" -name "${py_script}" -type f)
found_entrypoint=$(
while IFS='' read -r line ;do
echo -n $line
done <<< $(fgrep -A1 'entry_points={' ${py_script})
echo -n '}' && echo ""
)
found_entrypoint_dictionary=$(echo ${found_entrypoint} | awk -F'{' '{print $2}' | awk -F':' '{print $1}')
found_entrypoint_dictionary=$(echo ${found_entrypoint_dictionary//\"/})
found_dictionary_script=$(echo ${found_entrypoint} | awk -F'[' '{print $2}' | awk -F'=' '{print $1}')
found_dictionary_script=$(echo ${found_dictionary_script//\"/})
if ! [[ "${found_entrypoint}" =~ ^entry_points\=\{.* ]] ;then
echo "entry_points not found."
exit 1
fi
if [ "${found_entrypoint_dictionary}" == "${dictionary_to_match}" ] && [ "${found_dictionary_script}" == "${dictionary_script_to_match}" ] ;then
echo "${found_entrypoint}"
echo "True"
elif [ "${found_entrypoint_dictionary}" != "${dictionary_to_match}" ] || [ "${found_dictionary_script}" != "${dictionary_script_to_match}" ] ;then
echo "${found_entrypoint}"
echo "False"
else
echo "Somthing went wrong!"
exit 2
fi
exit 0
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
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
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 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.