2

I can run ps aux | grep python_script.py and get the details of the process running the script. I want to be able to run the same command from python script.

from subprocess import call
call(["ps", "aux"])

works well, however tried these lines but both returns error,

call(["ps", "aux", "|", "grep", "python_script.py"])
call(["ps", "aux", "| grep python_script.py"])

Returns error, can someone please advise me on how to run ps aux | grep python_script.py from command line

Paullo
  • 2,038
  • 4
  • 25
  • 50
  • Please read well b4 commenting, I asking of how to pass more arguments, that is a simple case which is NOT application to me. I have seen that solution but still did not solve my problem. Simple call(["ps", "aux"]) works, but I have more argument to pass – Paullo Jan 20 '18 at 10:54
  • Why are you using `grep` instead of just filtering the `ps` output in Python code? That would avoid the need for a shell pipeline at all. – Daniel Pryden Jan 20 '18 at 11:16

1 Answers1

1

If you are not too considerate about security you can set shell argument to True. It will then instead of a list, take a string as the command. In that way it act's like a shell.

from subprocess import call
call("ps aux | grep python_script.py", shell=True)
user1767754
  • 23,311
  • 18
  • 141
  • 164
  • Thanks @user1767754 that works, please is there a way I can pass the returned to a value and possibly decide the correct PID from the list returned. I tried result = call("ps aux | grep python_script.py", shell=True). But print (result) is 0 – Paullo Jan 20 '18 at 11:01
  • The linked duplicate already shows how to do this. Or you could read the documentation on the Python `subprocess` module. There are several well-documented ways to get the output of the subprocess, using `check_output`, `communicate`, or the `stdout` stream directly. – Daniel Pryden Jan 20 '18 at 11:20
  • @Paullo What are you exactly trying to do, get the `PID` of the running process? – user1767754 Jan 20 '18 at 20:08