Conditionally set an arg in launch if directory exists
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
andoptenv
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:
- I originally thought calling the script above from udev rule using
RUN
assignment to set environment variable if a dongle found. In this way apparently the env var gets set only for the process where the script starts. - The launch above fails since
config_path
is defined twice.
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:Used
eval
here to allow nesting.Hm. The problem would now of course be that if
DONGLE_PLUGGED
is notunset
upon removal of the dongle, this won't work.If
unset
ting is difficult/error prone/undesirable, perhapsparam
withcommand
and then a Python script that returns the path would be a feasible approach.