简体   繁体   中英

How to get the path of a unix domain socket using Python

So, I'm using the podman-py library for a project. In order to use it I need to provide a URI path for the libpod service. This URI has the following form:

"unix:///run/user/<some-id>/podman/podman.sock"

Currently, I get this URI by running this command on my server after installing podman-remote :

systemctl --user status podman.socket

And I get the following output from which I get the path to podman.sock :

● podman.socket - Podman API Socket
   Loaded: loaded (/usr/lib/systemd/user/podman.socket; disabled; vendor preset: enabled)
   Active: inactive (dead)
     Docs: man:podman-system-service(1)
   Listen: /run/user/0/podman/podman.sock (Stream)

Right now I have hardcoded this URI in my code. However more people will use this project and I would like to get the path dynamically, in case it varies from server to server. I can of course just execute the command and grep what I want using Python, but I was wondering if there is a better alternative before I go with this solution.

Thanks!

Ideally there'd be a systemctl module you could import which would do this without shelling out.

The info you need is the Listen element in the 'show' command's output:

$ systemctl --user show pulseaudio.socket|grep -i listen
Listen=/run/user/101346/pulse/native (Stream)

A quick-n-dirty hack to get this info could look like this:

import subprocess
args=["/usr/bin/systemctl", "--user", "show", "pulseaudio.socket"]
command = subprocess.Popen(args, stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
stdout, stderr = command.communicate()
lines = stdout.splitlines()
listen = [str(l) for l in allstatus if l.startswith(b'Listen') ]
mysocket = listen[0].split("=")[1].split(" ")[0]

which would show that my userid has this for the pulseaudio socket:

>>> mysocket
'/run/user/101346/pulse/native'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM