ofek / userpath

Cross-platform tool for adding locations to the user PATH, no elevated privileges required!
MIT License
151 stars 20 forks source link

`utils.get_parent_process_name()` does nothing if no `psutil` package is present #30

Closed itsayellow closed 3 years ago

itsayellow commented 3 years ago

https://github.com/ofek/userpath/blob/a763ba69a90368f69e3a054a8ceadb775ac78ff0/userpath/utils.py#L53-L54 This code is never run if there is no psutil in the environment. In addition, this ps command does not work in Windows. The reason this isn't an error is because that code never gets run (even though the intent is that it would) because of the explanation below. Probably these two lines should just be removed.

The code for get_parent_process_name() in utils looks like it is supposed to fall back on these two lines if there is no psutil in the environment:

ppid = os.getppid()
return subprocess.check_output(['ps', '-o', 'cmd=', str(ppid)]).decode('utf-8').strip()

However, these lines will never execute if there is no psutil present. This is because the statement

if psutil:

will raise a NameError: name 'psutil' is not defined Exception, which will jump immediately to the except Exception: pass and the function will then proceed to return an empty string ''.

I tried a version to remedy this, that uses the following code at the top of the file to try and import psutil:

try:
    import psutil
except Exception:
    psutil = None

This fixes the NameError for psutil, but the next problem is that the syntax for ps needs to use the form ps -o command= <pid> to be applicable to both macOS (BSD) and linux.

However, I couldn't figure out the form that would work in Windows.

itsayellow commented 3 years ago

Oh I just see that this function is never executed for Windows. So it's possible the subprocess could be made to work over all macOS, linux, BSD, etc.