How I can pass bash variable inside python command?

Viewed 25

I want to pass variable server inside python command and read the python command result portStatus variable out from command.

for server in `echo $dnsServers | awk -F";" '{print $1" "$2" "$3" "$4" "$5" "$6}'`
  do
    python3 -c 'import socket;
    a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
    host=("$server", 53); 
    portStatus=a_socket.connect_ex(host);'
  done
echo $portStatus


Getting this error :

Traceback (most recent call last):
  File "<string>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
Traceback (most recent call last):
  File "<string>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
Traceback (most recent call last):
1 Answers

Relying on expanding the variable inside the Python statement is not a good idea since the statement need to be given as a string where shell variables can be expanded (i.e. use double quotes not single quotes) and that everything needs to be properly escaped so that the shell does not interpret things it is not supposed to. This can be very complex.

Much easier is to give the variables as an additional command line argument and then access the argument with sys.argv, like this:

for i in a b c d ; do 
    python3 -c 'import sys; print(sys.argv[1]);' $i
done

To get a single line value back catch the result of the python code into a shell variable:

for i in a b c d ; do 
    foo=`python3 -c 'import sys; print("in python: " + sys.argv[1]);' $i`
    echo "in shell: $foo"
done

The result from this:

in shell: in python: a
in shell: in python: b
in shell: in python: c
in shell: in python: d
Related