Conditionally set an arg in launch if directory exists

asked 2018-01-28 15:23:44 -0600

130s gravatar image

updated 2018-01-28 15:58:38 -0600

My app refers to a folder where a bunch of config files are. Ideally a .launch file refers to that folder on a USB dongle if it's plugged in, but if not then fall back on to a folder on HDD. What's the best way to achieve this? Mountpoint's path on the dongle is always the same. I can customize udev rule for this dongle.

I'm thinking to experiment:

  • Customize setup.bash and call a script like the following to see if mountpoint exists or not. If it does, export an env var.
  • Then use if and optenv in launch to see if the environment variable is set or not.

#!/usr/bin/env python

import os
import psutil
import subprocess
import syslog

def x_dongle_plugged():
    """                         
    @return: True if dongle's mountpoint found.
    @rtype: bool
    """

    PATH_DONGLE_YY = "/media/ZZZZZ/cm-yy"
    # https://stackoverflow.com/a/39124749/577001
    mount_points = {el.mountpoint: el for el in psutil.disk_partitions(all=True)}
    try:
        partition_dongle = mount_points[PATH_DONGLE_YY][0]
        print("Mountpoint {} found at the partition {}.".format(PATH_DONGLE_YY, partition_dongle))
    except KeyError as e:
        syslog.syslog("x dongle's mount point {} not found.".format(PATH_DONGLE_YY))
        syslog.syslog(str(e))
        raise e

if __name__ == "__main__":
    x_dongle_plugged()

Launch file example:

<?xml version="1.0" ?>
<launch>
  <arg name="config_path" default="$(env HOME)/.config/xx" />
  <group if="$(optenv DONGLE_PLUGGED false)">
    <arg name="config_path" default="/media/ZZZZZZ/cm-yy/.config/xx" />
  </group>
  :

UPDATE: Some things I noticed:

edit retag flag offensive close merge delete

Comments

Would it not be an option to set DONGLE_PLUGGED to the actual path itself (obviously give the variable a better name)? Then the arg assignment becomes:

<arg name="config_path" value="$(eval optenv('DONGLE_PLUGGED', env('HOME')+'/.config/xx'))" />

Used eval here to allow nesting.

gvdhoorn gravatar image gvdhoorn  ( 2018-01-29 02:35:13 -0600 )edit

Hm. The problem would now of course be that if DONGLE_PLUGGED is not unset upon removal of the dongle, this won't work.

If unsetting is difficult/error prone/undesirable, perhaps param with command and then a Python script that returns the path would be a feasible approach.

gvdhoorn gravatar image gvdhoorn  ( 2018-01-29 02:48:18 -0600 )edit