简体   繁体   中英

python subprocess grep returns zero

I'm trying to count the number of times the string OW appears in a file with the following scrip,

import subprocess
subprocess.call("grewp Ow file.txt | wc -l", shell=True)

but it always returns the correct answer followed by zero

>>> subprocess.call("grep OW production_run.gro | wc -l", shell=True)
2638
0
>>> 

and when I try to declare a variable with it, it stores 0. Does anyone here have any idea of why that's happening and how to fix it?

Python's docs about subprocess.call

Run the command described by args. Wait for command to complete, then return the returncode attribute.

Try check_output instead

based on document subprocess.check_output :

Run command with arguments and return its output as a byte string.

Thus you can use this:

count = int(subprocess.check_output("grewp Ow file.txt | wc -l", shell=True))

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