0

I want to change the built-in file I/O methods for any given python application without having to modify its code. Is this possible?

Maybe using Python's subprocess?

For example, I want a file object's read() method to actually call my custom_read() method instead, but without having to change any code in the program calling the read().

martineau
  • 119,623
  • 25
  • 170
  • 301
  • No, you can't change a program's code without, well, changing its code. – chepner Jun 03 '19 at 17:14
  • Possible duplicate of [Override module method where from...import is used](https://stackoverflow.com/questions/10829200/override-module-method-where-from-import-is-used) – Masoud Jun 03 '19 at 17:17
  • @chepner Yes you can, with monkeypatching. https://stackoverflow.com/a/5626250/494134 – John Gordon Jun 03 '19 at 17:24
  • @JohnGordon That's a form of changing the code. – chepner Jun 03 '19 at 17:30
  • He specifically said _without having to change any code in the program calling the read()_, meaning it's okay to change code elsewhere. – John Gordon Jun 03 '19 at 17:33
  • @chepner: In general, I don't think monkey-patching is a form of changing the code. However I doubt that it would be possible to change the `read()` method of a Python built-in like a `file` object. – martineau Jun 03 '19 at 18:02
  • @martineau you can [override `open`](https://stackoverflow.com/a/45950329/5858851)...there's probably a hacky solution that involves writing your own `open`, then importing it, then running the contents of the original script. – pault Jun 03 '19 at 18:09
  • @pault: I don't think overriding `open()` like and monkey-patching it in so it was used for "for any given python application" is possible. – martineau Jun 03 '19 at 18:25

0 Answers0