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?

4
  • stackoverflow.com/questions/4675728/… Commented Jun 24, 2020 at 13:38
  • 1
    Does this answer your question? Redirect stdout to a file in Python? Commented Jun 24, 2020 at 13:42
  • Thanks but I now get on console '.................... ' Commented Jun 24, 2020 at 13:58
  • 1
    You can just use verbose=0 on your send command to remove the logs... instead of doing a redirection :p Commented Jun 25, 2020 at 8:58

1 Answer 1

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') 
Sign up to request clarification or add additional context in comments.

5 Comments

I tried the same but now get on console '.................... ' instead of 'Sent 1 packets. .'
Not having your code I will suggest to try to use the context manager for the whole block of code. Seems that there is a print performed somewhere else.
Here the raw code output: >>> sendp(packet, iface='Intel(R) Ethernet Adapter') . Sent 1 packets.
Probably scrapy is also writing to stderr.
I tried also to redirect the stderr, but it does not work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.