1

I have problem execute this code here

subprocess.check_output(['ps -ef | grep ftp | wc -l'],env=environ,shell=True) 

When I execute from terminal

ps -ef | grep ftp | wc -l 

I get "1" as output which is fine.

Now, I execute same code from my python files as subprocess.check_output and it gives me 2. That is strange. Any Ideas why is it happening. Here is the complete code:

 def countFunction(): environ = dict(os.environ) return subprocess.check_output(['ps -ef | grep ftp | wc -l'],env=environ,shell=True) count = countFunction() print count 

EDIT: Just to update , I do not have any ftp connections on.So command line is printing 1 on command which is fine. Thanks Arvind

6
  • Does your python process have the name ftp in it by any chance? Commented May 14, 2015 at 16:23
  • No, just the above code. No ftp text in the process executed Commented May 14, 2015 at 16:26
  • You can fix this easily by simply running ps -ef | grep ftp and finding where the extra process is coming from. Commented May 14, 2015 at 16:39
  • Hint: ps -ef | grep ftp might, depending on timing, find not only ftp, but also grep ftp... Commented May 14, 2015 at 17:07
  • @twalberg: Both processes are created before they run. Otherwise there would be no way to connect their pipes. Commented May 14, 2015 at 17:11

1 Answer 1

2

The grep command will find itself:

$ ps -ef | grep ftp wallyk 12546 12326 0 16:25 pts/3 00:00:00 grep ftp 

If you don't want that, exclude the grep command:

$ ps -ef | grep ftp | grep -v ftp $ 

It would be better to drop the -f switch to ps so that the command line arguments are not searched. That way, it won't find the grep ftp running:

$ ps -e | grep ftp | wc -l 
Sign up to request clarification or add additional context in comments.

7 Comments

He doesn't have any FTP processes running, so he wants it to return only 1.
Thanks for your reply wallyk . Yes but with python code , your above command does not print anything, even if ftp is on.
@MartinKonecny: Exactly! By excluding the grep command from the results, only other processes with ftp in their arguments will count.
Thank you wallyk, -f flag was causing problem. Cheers!
@wallyk any ideas why output of ps -e | grep ftp | wc -l shows 1 in command line output while 2 form python code!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.