I have a bash script, a.sh , and in it I have call a python script b.py . The python script calculates something, and I want it to return a value that will be used later in a.sh . I know I can do
In a.sh:
var=`python b.py`
In b.py:
print x # when x is the value I want to pass
But this is not so convenient, because I also print other messages in b.py
Is there any better way to do it?
Edit:
What I'm doing now is just
var=`python b.py | tail -n 1`
It means I can print many things inside b.py, but only the last line (the last print command, assuming it doesn't contain "\n" in it) will be stored in var.
Thanks for all the answers!
You'll need to share what you've tried so far, or what the current code you have is. Try to keep it to the relevant portions, and not the entire script. Pass the variables into python as command line arguments then use something like getopt to parse the command line arguments within your python script.
We can make use of the bash script to run the Python script in macOS/Ubuntu. Both these operating systems support bash scripts.
The best choice is using the argparse module, which has many features you can use. So you have to parse arguments in your code and try to catch and fetch the arguments inside your code. You can't just pass arguments through terminal without parsing them from your code.
How to store a python script output to a variable using publish in workflow scripts. When you use Python script as action, you must implement run() method from BaseAction class. This method's return value can be assigned to the variable in the workflow. where msg being a variable declared in the orchesta workflow.
I would print it to a file chosen on the command line then I'd get that value in bash with something like cat
.
So you'd go:
python b.py tempfile.txt
var=`cat tempfile.txt`
rm tempfile.txt
[EDIT, another idea based on other answers]
Your other option is to format your output carefully so you can use bash functions like head
/tail
to pipe only the first/last lines into your next program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With