0

I have a bash script:

#!/bin/bash
while :
    do
        nc -l -p 30003 | python3 script.py 
    done

I want that listening works all time.

nc localhost 30003 # works, fine type something Ctrl+C

Try again nc localhost 30003 # not working

So, after socket closed first time, it never open again..

How can I fix it?

  • Also I have many defined function inside python script, so I donw want to run it from the beginning. Is it possible?

Thanks.

1
  • Is script.py written in a way that it will not close the reading end of the pipe? If so, then you can tell nc to keep listening by adding -k option to it. Commented Jan 5, 2017 at 4:25

1 Answer 1

1

The problem is that nc -l -p 30003 is not run again before python3 script.py finishes. After Ctrl+C nc localhost 30003 has no listening nc to connect to. If you replace python3 script.py with cat the nc server will restart. So the simple solution would be to have script.py exit.

I assume that you have a state that you want to save. One possibility is to have a file with the state (variables etc.) saved as JSON. Another is to have nc write the output to a file, and have script.py read from that file.

If you have the time, and want to learn some networking, I recommend to look at the python socket API. You can make script.py act as a server and read the data directly from the connection endpoint, rather than going through nc.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.