简体   繁体   中英

Output to console after run command 'launchctl…' from Pycharm. For Python 3.7

I run command:

'launchctl list | grep -v com.apple'

and my issue to check if certain process is up.

Now I can execute it only in next way: command --> save answer to file.txt --> check if this process in this txt.

But, I want to optimize it.

It should it be like this:

if(statement that my process is up):
    do something
else:
    do something else

Please, tell me, if another (easier way) way to check it?

You can use the subprocess module to invoke the command from within your Python script and capture its output:

import subprocess

stdout = subprocess.check_output(['launchctl', 'list'], universal_newlines=True)
if 'yourapp' in [line.strip() for line in stdout.splitlines() if 'com.apple' not in line]:
    do something
else:
    do something else

Points to note here:

  • There's no need to pipe through grep because we can do the processing in Python.
  • We also don't need to invoke a shell, and can start launchctl directly by passing a list of arguments, rather than a single string. It doesn't matter much in this example, but as soon as you want to add parameters and they might contain special characters, going through the shell is best avoided.
  • check_output raises an exception if the program fails with a nonzero exit code.
  • universal_newlines=True decodes the output (which is normally bytes ) into a string. A more sensibly named argument text was added in Python 3.7, so you can use that if you don't need compatibility with older Pythons.

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