Python Forum

Full Version: converting scripts to be functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have many scripts that output text of what they find or figure out. i'd like to re-implement them as functions so other script can access the same information. that means some means to send the output to the caller. there are so many ways to do this. i'd like to know which is the recommended pythonic way. would that be to make a generator to yield the output one line at a time?

what if the original script does some of its output by running commands and letting their output just mix in at the right place?
Here's a documentation page that explains the syntax you need to use as the first line of your function to describe your function's interface. Once you've written a function, you call it the same way you'd call any of the functions included in MATLAB like max, clc, disp, etc.
@elenaflorence87, the links you share are MATLAB docs. This is python forum and your post is irrelevant. Please, consider if your post will contribute to discussion before you post.
I don't think there is a 'recommended pythonic' way to do it. The simplest way, as the script outputs serialized data, is perhaps to give the function an open file object argument where the output will be written instead of stdout. If the script uses other commands, you could capture their output and write them to this file object as well.

The next level is perhaps to output structured data that client code wouldn't have to parse. For example the 'ls' command outputs a sequence of directory entries. One could imagine a functional version that returns an iterable of Entry objects in a way similar to os.scandir(). It requires more transformation of the original code to parse its output, so you could do it gradually.

Some other issues may arise, for example some programs may assume that they are running in a terminal and behave differently when they are called from a script.
these are script i have written in the past. i don't recall making anything check for type of output device. an output file certainly can be a way to provide it to the caller as an open file it can read. i could make a reader and parser as a generator and just run the original script as a subprocess with a pipe.