from argparse import ArgumentParser, FileType
from sys import stdout
from signal import signal, SIGPIPE, SIG_DFL
import pandas as p

def main():
    parser = ArgumentParser(description='Transform a "pickle" to a csv file')
    parser.add_argument(dest="input",      help = "input pickle path", type = FileType('rb'))
    parser.add_argument(dest="output",  nargs="?",   help = "output csv path", type = FileType('w'))
    parser.add_argument("-r", "--row-names", dest = "rownames", help = "include row names in csv; "
                        "needed to faithfully reproduce some dataframes. "
                        "Use -v to check information about dataframe", action = "store_true")
    parser.add_argument("-v", "--verbose", dest = "verbose", action ="store_true", 
                        help="print information about dataframe and process")
    args = parser.parse_args()

    if args.output is None:
        args.output = stdout

    if args.verbose:
        print("Reading pickle")

    ptc = p.read_pickle(args.input)

    if args.verbose:
        print(ptc.info())
        print("Saving as csv")

    signal(SIGPIPE, SIG_DFL) # Prevent broken pipe errors when piping to less or head
    ptc.to_csv(args.output, index = args.rownames)


    args.input.close()
    args.output.close()


if __name__ == "__main__":
    main()
