# Python block help

**URL:** <https://www.ruby-forum.com/t/python-block-help/233561>\
**Category:** GNU Radio\
**Created:** [December 24, 2014, 12:22pm UTC](https://www.ruby-forum.com/t/python-block-help/233561 "2014-12-24T12:22:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![addis\_a](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/c4cdca/32.png) [@addis\_a](https://www.ruby-forum.com/u/addis_a)\
**Post date:** [December 24, 2014, 12:22pm UTC](https://www.ruby-forum.com/t/python-block-help/233561/1 "2014-12-24T12:22:42Z")

</div>

Hi list,

I am writing a custom python block that should take complex input, check  
magnitude of incoming samples and if the magnitude is greater than a  
threshold value, the block should pass that sample otherwise the block  
just  
drop the samples. As this is an arbitrary ratio block I derived it from  
gr.block and set\_auto\_consume(False).

However I get intermittent zeros in output stream of my custom block.  
Below  
is the code

from gnuradio import gr  
import gnuradio.extras  
import math  
import numpy as np

class sdr\_pass\_valid(gr.block):  
“”"  
“”"  
def **init** (self,threshold):  
gr.block. **init** (  
self,  
name = “VALID”,  
in\_sig = [np.complex64],  
out\_sig = [np.complex64],  
)  
self.set\_auto\_consume(False)

```
self.threshold = threshold
def forecast (self,noutput_items,ninput_items_required):
for i in range(len(ninput_items_required)):
    ninput_items_required[i] = noutput_items

def work(self, input_items, output_items):

    in0 = input_items[0][:len(output_items[0])]
out0= output_items[0]
    nread = self.nitems_read(0) #number of items read on port 0
    ninput_items = len(in0)
j=0
for i in range(0,ninput_items):
    if np.absolute(in0[i]) >= self.threshold :
        out0[j] = in0[i]
        j = j + 1
    self.consume(0,ninput_items)
self.produce(0,len(out0))
    return 0
```

---

<div class="post-metadata">

**Author:** ![bob\_wole](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/b4bc9f/32.png) [@bob\_wole](https://www.ruby-forum.com/u/bob_wole)\
**Post date:** [December 27, 2014, 8:21am UTC](https://www.ruby-forum.com/t/python-block-help/233561/2 "2014-12-27T08:21:38Z")

</div>

Hi Bob,

I think you’ve introduced the “j” variable to keep count of how many  
items you’re going to produce, but then just tell the scheduler you’ve  
produced as many items as he offered you to do. Replace  
self.produce(0,len(out0))  
by  
self.produce(0,j).  
Also, you consume ninput\_items every for loop iteration, so  
ninput\_items^2 per work run. That’s not right; do it only once, after  
the loop.

Greetings,

Marcus
