I'm trying to obtain the processID of pcmanfm
like this:
pgrep -f "pcmanfm"
When pcmanfm
is not running, the command above returns nothing (as I expect).
However, when I run the command from python, it returns a process ID even when pcmanfm
is not running:
processID = os.system('pgrep -f "pcmanfm"')
Furthermore, if you run the command above multiple times at a python3 prompt, it returns a different processID each time. All the while, pcmanfm
has been closed prior to these commands.
>>> processID = os.system('pgrep -f "pcmanfm"')
17412
>>> processID = os.system('pgrep -f "pcmanfm"')
17414
>>> processID = os.system('pgrep -f "pcmanfm"')
17416
This is really messing up my ability to launch pcmanfm
if it isn't currently running. My script thinks it is running when it isn't.
Why is this happening?
I'm actually encountering this issue in an Autokey script that I've attempted to write based on this video I watched. Here's my current script:
processID = system.exec_command('pgrep -f "pcmanfm" | head -1',True)
dialog.info_dialog("info",processID)
if (processID):
cmd = "wmctrl -lp | grep " + processID + " | awk '{print $1}'"
windowID = system.exec_command(cmd,True)
# dialog.info_dialog("info",windowID)
cmd = "wmctrl -iR " + windowID
#dialog.info_dialog("info",cmd)
system.exec_command(cmd,False)
else:
#os.system("pcmanfm /home/user/Downloads")
cmd = "/usr/bin/pcmanfm /home/user/Downloads"
system.exec_command(cmd,False)
The problem is, I keep getting processIDs even when pcmanfm
isn't running. The script properly focuses pcmanfm
if it is running, but it won't launch it if it isn't.
Update: I finally got this script to work by taking out -f
and replacing it with -nx
(from @they 's advice). Also, I added some exception handling to ignore autokey exceptions caused by empty output that's expected. Additionally, I converted it to a (more flexible) function so that it will service a wider variety of commands/applications:
import re
def focusOrLaunch(launchCommand):
appName = re.findall('[^\s/]+(?=\s|$)',launchCommand)[0]
processID = None
try:
processID = system.exec_command('pgrep -nx "' + appName + '"',True)
except Exception as e:
#dialog.info_dialog("ERROR",str(e))
pass
#dialog.info_dialog("info",processID)
if (processID):
cmd = "wmctrl -lp | grep " + processID + " | awk '{print $1}'"
windowID = system.exec_command(cmd,True)
# dialog.info_dialog("info",windowID)
cmd = "wmctrl -iR " + windowID
#dialog.info_dialog("info",cmd)
system.exec_command(cmd,False)
else:
system.exec_command(launchCommand,False)
cmd = "/usr/bin/pcmanfm ~/Downloads"
focusOrLaunch(cmd)