Skip to content

Instantly share code, notes, and snippets.

Created April 9, 2023 18:58
Show Gist options
  • Save ghutchis/940b3f094969c515d02074bd9cb92c2b to your computer and use it in GitHub Desktop.
Save ghutchis/940b3f094969c515d02074bd9cb92c2b to your computer and use it in GitHub Desktop.
Avogadro2 XYZ directory to PNG
import json
import socket
import struct
import glob
import tempfile
import os
class Connection:
'''Process a JSON-RPC request'''
def __init__(self, name="avogadro"):
Connect to the local named pipe
:param name: The name of the named pipe.
# create socket
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# connect
self.sock.connect(tempfile.gettempdir() + "/" + name)
def send_json(self, obj):
Send a JSON-RPC request to the named pipe.
:param obj: The JSON-RPC request object.
def send_message(self, msg):
Send a message to the named pipe
:param msg: The message to send.
size = len(msg)
header = struct.pack(">I", size)
packet = header + msg.encode("ascii")
def receive_message(self, size=1024):
Receive a message from the named pipe.
:param size: The maximum size of the message to receive.
packet = self.sock.recv(size)
return packet[4:]
def recv_json(self):
'''Receive a JSON-RPC response'''
msg = self.recv_message()
return json.loads(msg)
except Exception as exception:
print("error: " + str(exception))
return {}
def close(self):
'''Close the socket to the named pipe'''
def sendMessage(method, fileName):
conn = Connection()
params = {"fileName": fileName}
conn.send_json({"jsonrpc": "2.0", "id": 0, "method": method, "params": params})
reply = str(conn.receive_message())
return reply
if __name__ == "__main__":
conn = Connection()
# loop through all .xyz files in the current directory
# and save them as .png files
cwd = os.getcwd()
for fileName in glob.glob("*.xyz"):
# open the file
print("Opening " + fileName)
path = cwd + "/" + fileName
print(sendMessage("openFile", path))
# save the screenshot
print(sendMessage("saveGraphic", path[:-4] + ".png"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment