0

In my Django web app I want to convert an uploaded csv file into a markdown table. I searched around and found this library that does that. However it only has instructions on how to do it from the command line, like so: csvtomd input.csv > output.md, but I want to use it inside my python file (views.py) and I don't know if it is even possible. I understand there might be another way I can get this specific task done, but I want to know if it is possible to use the functionality of such a library, that is accessible from the commandline, inside my python file instead.

I came across this question; however, I after something specifically for using a python library inside a python file, and not general prompt commands.

Sameer Zahid
  • 193
  • 1
  • 11

1 Answers1

1

It Depends (TM). If a command line script is written well, with implementation inside of functions, a separate function to process command line arguments and a if __name__ == "__main__": clause to make it import safe, then you can put it somewhere in the python path, import it, and use the defined functions. That appears to be the case here. The author did a good job of separating out the implementation into csv_table and md_table.

This script also appears to be written to handle input on stdin and output on stdout. This means you can run it as a script via subprocess.Popen and pipe the data through.

I can't give specific examples because I don't know what form your data is in.

tdelaney
  • 55,698
  • 4
  • 59
  • 89
  • Skimming thru the code of the [`csvtomd`](https://github.com/mplewis/csvtomd/blob/master/csvtomd/csvtomd.py) - from the code view it isn't really expected to be called outside CLI. But it's a python module nonetheless so using func `csv_to_table` and feeding the output into `md_table` function of the module should yield workable results. (hint: `from csvtomd.csvtomd import csv_to_table, md_table`) – Wereii Jul 31 '20 at 00:01
  • @Wereii That is what I ended up doing in this case. I imported the library and just used its individual function. I'm still looking into what makes a library accessible from inside a .py file and studying this answer. – Sameer Zahid Jul 31 '20 at 00:16
  • Syntactically, scripts and modules are the same thing. Its a module (library) if its somewhere the python import system can find it. A well behaved script like I mention can just as easily be a module. Conversely, modules can also be called as scripts (e.g., `python -m pip install`) if they have the right function calls. For installed products, the difference is that scripts are on the PATH so that the operating system can find them whereas modules are in one of the python-aware directories. You can see that with `sys.path` - which is somewhat misnamed! – tdelaney Jul 31 '20 at 01:09