I assume that you wish to publish this as a Kindle book or you would not be going to the trouble of trying to make it work.
Extracting text from an e-book can cause problems, especially for things like software that must not be changed in the process. Also not everyone will have Kindle for PC or Mac. Those using a Kindle e-reader or tablet to read your book will need another way to obtain the sample.
I think that you will be better off having an author website that you reference in your book where you can have the code samples available for download by readers. That would also be a good place to advertise your books and yourself as an author.
This topic might be a better ft for the
Kindle Formats forum. That is where the coding and publishing of Kindle books is discussed.