Search code examples
pythonpython-3.xvisual-studiopycharminteractive-brokers

How to write to a file by using (or changing) print using Python 3.x


Im using an API from Interactive Brokers to get historical data and I am using their code to download the data.

The code uses the print function to output the data to the terminal, but I would like to redirect it to a file (lets call that file StockData.txt)

The code I am using is:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract

class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def error(self, reqId, errorCode, errorString):
        print("error: ", reqId, " ", errorCode, " ", errorString)

    def historicalData(self, reqId, bar):
        print("HistoricalData. ", reqId, " Date:", bar.date, "Open:", bar.open, "High:", bar.high, "Low:", bar.low, "Close:", bar.close, "Volume:", bar.volume)

def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)

    contract = Contract ()
    contract.symbol = "AAPL"
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"

    app.reqHistoricalData(0, contract, "", "1 D", "1 min", "TRADES", 0, 1, False, [])

    app.run()

if __name__ == "__main__":
    main()

Like I said, I would like the API to write to StockData.txt, but I am unsure how to do this since it's not my code and I am not that savvy in Python.

Could anyone help me out here? Thanks!


Solution

  • while it would probably be better to do output redirection:

    python my_script.py > outputfile.txt
    

    to actually overwrite any function is pretty simple:

    def print_to_file(*args):
        with open('text.txt', 'a') as fh:
            fh.write(' '.join(map(str,args)))
    print = print_to_file
    

    just plop the above lines of code somewhere high in you script
    this is not the recommended way though, because it will only overwrite print in the current script and not in the imported modules which may also be printing

    A better way is to change your stdout:

    import sys
    sys.stdout = open('text.txt', 'a')