Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to run bash script in python

import subprocess
print "start"
subprocess.call("sleep.sh")
print "end"
Comment

python code in bash script

#!/bin/bash
/usr/bin/python /absolute/path/to/your/disk.py
Comment

Shell script to run python

In the file job.sh, put this
#!/bin/sh
python python_script.py
Execute this command to make the script runnable for you : chmod u+x job.sh
Run it : ./job.sh
Comment

python code in bash script

#!/bin/sh
python disk.py
Comment

run python script inside bash script

#/bin/bash
#append python script to file
tee .tempfile.py >/dev/null <<EOF
#!/bin/env python3
from scipy import integrate
x2 = lambda x: x**2
print(integrate.quad(x2, 0, 4))
EOF
#execute using python
python3 .tempfile.py
#remove file after exectution
rm -rf .tempfile.py
Comment

python code in bash script

You can use heredoc if you want to keep the source of both bash and python scripts together. For example, say the following are the contents of a file called pyinbash.sh:

#!/bin/bash

echo "Executing a bash statement"
export bashvar=100

cat << EOF > pyscript.py
#!/usr/bin/python
import subprocess

print 'Hello python'
subprocess.call(["echo","$bashvar"])

EOF

chmod 755 pyscript.py

./pyscript.py
Now running the pyinbash.sh will yield:

$ chmod 755 pyinbash.sh
$ ./pyinbash.sh
Exe
Comment

python code in bash script

The simplest approach is to just save the python script as, for example script.py and then either call it from the bash script, or call it after the bash script:

#!/usr/bin/env bash
echo "This is the bash script" &&
/path/to/script.py
Or

script.sh && script.py
Comment

python code in bash script

#!/bin/bash

PYCMD=$(cat <<EOF
from datetime import datetime

first_day_of_new_year = datetime(2022, 1, 1)

days_remaining = (first_day_of_new_year - datetime.now()).days
print('{} days remaining in this year'.format(days_remaining))
EOF
)

python3 -c "$PYCMD"
Comment

python code in bash script

#!/bin/bash

# Here are some embedded Python examples using Python3.
# They are put into functions for separation and clarity.


# Simple usage, only using python to print the date.
# This is not really a good example, because the `date`
# command works just as well.
function date_time {
    python3 - <<END
from datetime import datetime
print('Current date:')
print(datetime.now())
END
}
# Call the python code.
date_time

# Sending a variable to Python from BASH
function env_args {
    # Put an environment arg into Python.
    # Must be on the same line as the command.
    TESTARG="My Value" python3 - <<END
from os import environ
print('Your environment arg: {}'.format(environ.get('TESTARG', 'missing!')))
END
}
env_args

# Retrieve output from Python and put it into a BASH variable.
# This uses a subshell to retrieve whatever python prints out.
function val_from_python {
    # Get a python value from BASH.
    pythonval="$(python3 - <<END
import os
print('cwd: {}'.format(os.getcwd()))
END
)"
    echo "Python value is: $pythonval"
}
val_from_python

# You can put small python snippets directly into your shell files.
# Here's an example using `urllib` to download some html, and then
# using it in BASH. 

# (granted that you could do this in Python itself,
#  or you could write it all in BASH, but this is just an example.)
function python_power {
    # Grab the html from python.org's PEP8 page and save it to a bash variable.
    # On error, the output will be a basic HTML page with the error message.
    local pythonval="$(python3 - <<END
from urllib import request
try:
    resp = request.urlopen('http://legacy.python.org/dev/peps/pep-0008/')
    data = resp.read().decode('utf-8')
    print(data)
except Exception as ex:
    print("""
        <html>
<head>
<title>Error in python_power</title>
</head>

        <body>
There was an error retrieving that page: {}
</body>
""".format(ex))
END
)"
    # Print the content so it can be used by other commands.
    # (you also could've saved it to a global variable.)
    echo $pythonval
}

# Direct the output of this python function to a file.
# The html will not be styled correctly, because no css files are downloaded.
# But the point here is that you can have the full power of python without
# writing separate scripts. Small python snippets can be embedded and used
# from BASH itself.
outfile='pep8.html'
python_power > $outfile
if [[ -f $outfile ]]; then
    echo "New file was created: $outfile"
    google-chrome $outfile
else
    echo "Unable to create new file: $outfile"
fi
Comment

python code in bash script

#!/bin/bash

MYSTRING="Do something in bash"
echo $MYSTRING

python - << EOF
myPyString = "Do something on python"
print myPyString

EOF

echo "Back to bash"
Comment

python code in bash script

#!/bin/bash
python3
print("Hello World")
exit()
echo "The execution is completed"
Comment

python code in bash script

read -p "How many numbers: " n
python <<END
for i in range($n):
    print(i)
print("Literal dollar sign $")
END
Comment

python code in bash script

*2 Example of the dangers of temp files. DO NOT USE THIS CODE

cat >/tmp/python-script <<END
for i in range(10):
    print(i)
END
python /tmp/python-script
If someone else creates /tmp/python-script first, this shell script won't even stop if it fails to overwrite the file. A malicious user on the system could make a harmful Python script which will run instead of the intended script.
Comment

python code in bash script

There are ways to do this safely, but the simplest way would be to create the files in the current working directory or in a dedicated directory in the home directory.

cat >dopythonstuff <<END
...
END
python dopythonstuff
rm dopythonstuff
Comment

python in bash script

Just pass a HereDoc to python -.

From python help python -h:
-      : program read from stdin

#!/bin/bash
MYSTRING="Do something in bash"
echo $MYSTRING

python - << EOF
myPyString = "Do something on python"
print myPyString

EOF

echo "Back to bash"
Comment

python in bash script

You can use heredoc if you want to keep the source of both bash and python scripts together. For example, say the following are the contents of a file called pyinbash.sh:

#!/bin/bash
echo "Executing a bash statement"
export bashvar=100

cat << EOF > pyscript.py
#!/usr/bin/python
import subprocess

print 'Hello python'
subprocess.call(["echo","$bashvar"])

EOF

chmod 755 pyscript.py

./pyscript.py
Now running the pyinbash.sh will yield:

$ chmod 755 pyinbash.sh
$ ./pyinbash.sh
Exe
Comment

PREVIOUS NEXT
Code Example
Python :: python enumerate in list comprehension with if statement 
Python :: vscode how to extend output size in jupyter notebook 
Python :: featch detail of subscription in stripe api 
Python :: locate certs path for python 
Python :: pandas : stratification (mean) 
Python :: python youtube view bot 
Python :: histogram plot seaborn 
Python :: organize order columns dataframe 
Python :: sum 1-50 
Python :: python capitilize 
Python :: playlist discordpy 
Python :: how to print a text in python 
Python :: How to test if a webpage is an image python requests 
Python :: plot every nth label in barplot 
Python :: platform.system() return value 
Python :: python set literal 
Python :: vectorindexer pyspark 
Python :: take space away from strings ion pyhton 
Python :: jupiter output 
Python :: qcut and cut function in python stack overflow 
Python :: hexing floats 
Python :: check if a string is a palindrome python 
Python :: train_ttest_split() 
Python :: client.futures exchange info() 
Python :: python boolean ungleich 
Python :: prime palindrome number in python 
Python :: plotly colors 
Python :: how to randomise a string in python 
Python :: how to make dice roll in python 
Python :: pyaudio 
ADD CONTENT
Topic
Content
Source link
Name
4+8 =