1

I want to embed a small python script inside a bash script so that I can send a json object to a socket. I have tried the following code:

python -c "$(cat << 'EOF'
import socket
import json

data = {'ip':192.168.1.150', 'status':'up'}

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 13373))
s.send(json.dumps(data))
result = json.loads(s.recv(1024))
print result
s.close()
EOF
)"

and this: python -c " import socket import json

data = {'ip':192.168.1.150', 'status':'up'}

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 13373))
s.send(json.dumps(data))
result = json.loads(s.recv(1024))
print result
s.close()
"

But I keep getting the following error:

data = {'ip':192.168.1.150', 'status':'up'}
                     ^
SyntaxError: invalid syntax

I'm assuming this is because bash is interpreting this, not python. I've tested the code in a python script, and it works. Also, do I need the -c option?

Apologies, I'm completely inexperienced in python, I've written some quite extensive bash scripting for the project I'm working on and need to send the output of these to sockets as json objects. Such a small snipped of embedded Python code seems by far the simplest answer, unless anyone has other suggestions.

Python version installed on CentOS Python 2.6.6

0

1 Answer 1

4

The problem that you're having that results in the SyntaxError is that you don't have an opening single quote on the IP value in the data dict. You have:

data = {'ip':192.168.1.150', 'status':'up'}

You need:

data = {'ip':'192.168.1.150', 'status':'up'}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @John. Coding at 3am and panicking my solution wasn't going to work. Appreciate your time and I should have noticed that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.