0

I have written a Python code where I call below Scappy API:

sendp(packet, iface=adapter_name)

The code works fine but issue is that it prints below line on console where the program is executing as many times the above command is called:

Sent 1 packets.                                                                                                         
.

I need to suppress the console output so I tried:

old_stdout = sys.stdout
sys.stdout = log_file_name

But then I get exception:

    sendp(packet, iface=adapter_name)
  File "C:\Python36\lib\site-packages\scapy\sendrecv.py", line 315, in sendp
    verbose=verbose, realtime=realtime, return_packets=return_packets)
  File "C:\Python36\lib\site-packages\scapy\sendrecv.py", line 289, in __gen_send
    print("\nSent %i packets." % n)
AttributeError: 'str' object has no attribute 'write'

How can achieve the objective?

Programmer
  • 8,303
  • 23
  • 78
  • 162

1 Answers1

0

You have this previously answered question if you want to redirect to file: Redirect stdout to a file in Python?

The following example for redirecting to a memory string (from python docs):

import io
from contextlib import redirect_stdout
f = io.StringIO()
with redirect_stdout(f):
    help(pow)
s = f.getvalue()

And the latter example (if you just want to suppress the sys.stdout), trying to understand how it works: print will try to access the write method of sys.stdout, so I will just replace it with a class that has a write method that does nothing.

>>> class R:
...     def write(*args, **kwargs):
...         pass

>>> from contextlib import redirect_stdout

>>> with redirect_stdout(R()):
...     print('ciao')

piertoni
  • 1,933
  • 1
  • 18
  • 30