[python] Call Python script from bash with argument

I know that I can run a python script from my bash script using the following:

python python_script.py

But what about if I wanted to pass a variable / argument to my python script from my bash script. How can I do that?

Basically bash will work out a filename and then python will upload it, but I need to send the filename from bash to python when I call it.

This question is related to python linux bash shell debian

The answer is


To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance

> python python_script.py var1 var2

To access these variables within python you will need

import sys
print sys.argv[0] # prints python_script.py
print sys.argv[1] # prints var1
print sys.argv[2] # prints var2

I have a bash script that calls a small python routine to display a message window. As I need to use killall to stop the python script I can't use the above method as it would then mean running killall python which could take out other python programmes so I use

pythonprog.py "$argument" & # The & returns control straight to the bash script so must be outside the backticks. The preview of this message is showing it without "`" either side of the command for some reason.

As long as the python script will run from the cli by name rather than python pythonprog.py this works within the script. If you need more than one argument just use a space between each one within the quotes.


Print all args without the filename:

for i in range(1, len(sys.argv)):
print(sys.argv[i])

Beside sys.argv, also take a look at the argparse module, which helps define options and arguments for scripts.

The argparse module makes it easy to write user-friendly command-line interfaces.


Embedded option:

Wrap python code in a bash function.

#!/bin/bash

function current_datetime {
python - <<END
import datetime
print datetime.datetime.now()
END
}

# Call it
current_datetime

# Call it and capture the output
DT=$(current_datetime)
echo Current date and time: $DT

Use environment variables, to pass data into to your embedded python script.

#!/bin/bash

function line {
PYTHON_ARG="$1" python - <<END
import os
line_len = int(os.environ['PYTHON_ARG'])
print '-' * line_len
END
}

# Do it one way
line 80

# Do it another way
echo $(line 80)

http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html


and take a look at the getopt module. It works quite good for me!


Use

python python_script.py filename

and in your Python script

import sys
print sys.argv[1]

use in the script:

echo $(python python_script.py arg1 arg2) > /dev/null

or

python python_script.py "string arg"  > /dev/null

The script will be executed without output.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to debian

E: Unable to locate package npm How to update-alternatives to Python 3 without breaking apt? What is difference between arm64 and armhf? github: server certificate verification failed "Call to undefined function mysql_connect()" after upgrade to php-7 Debian 8 (Live-CD) what is the standard login and password? How to set the locale inside a Debian/Ubuntu Docker container? ps command doesn't work in docker container Forwarding port 80 to 8080 using NGINX Switching users inside Docker image to a non-root user