Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute multiline python code from a bash script?

I need to extend a shell script (bash). As I am much more familiar with python I want to do this by writing some lines of python code which depends on variables from the shell script. Adding an extra python file is not an option.

result=`python -c "import stuff; print('all $code in one very long line')"` 

is not very readable.

I would prefer to specify my python code as a multiline string and then execute it.

like image 445
cknoll Avatar asked Oct 19 '16 23:10

cknoll


People also ask

How do I run a multiline code in Python shell?

Using a Backslash. The backslash (\) is an escape character that instructs the shell not to interpret the next character. If the next character is a newline, the shell will read the statement as not having reached its end. This allows a statement to span multiple lines.

How do I multi-line strings in bash?

Although Bash has various escape characters, we only need to concern ourselves with \n (new line character). For example, if we have a multiline string in a script, we can use the \n character to create a new line where necessary.

Can you run a Python script in bash?

How do I run a Python script from bash terminal? Running a Script Open the terminal by searching for it in the dashboard or pressing Ctrl + Alt + T . Navigate the terminal to the directory where the script is located using the cd command. Type python SCRIPTNAME.py in the terminal to execute the script.


1 Answers

Use a here-doc:

result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
like image 84
Barmar Avatar answered Oct 08 '22 16:10

Barmar