Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn python script into a function

Assume I wrote a script morning.py which does a simple print statement

# morning.py
print 'Good morning'

Some hours later I've realized that I have to use this script in another script named evening.py. I am aware of two options. First, to invoke morning.py as a subprocess

# evening.py
import subprocess
import shlex
process = subprocess.Popen(shlex.split('python morning.py'))
process.communicate()

This is the way I've initially chosen. The problem is that I want to pack my program (morning + evening) into a single executable. And to my understanding, from the exe file such call just won't work.

Another option is to turn module morning into a function. For instance, like that

# morning.py
def morning_func():
   print 'Good morning'

Then I can simply call this function from the evening module

# evening
import morning
morning.morning_func()

Here the problem is that unlike morning my actual initial script is quite extended and messy. There is no single function that I can execute to simulate script running flow. Wrapping the whole script in a function just does not feel right.

What are possible solutions?

like image 466
Weather Report Avatar asked May 19 '16 14:05

Weather Report


People also ask

How do I turn a Python program into a function?

Basic Syntax for Defining a Function in Python In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.

What is __ main __ in Python?

__main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It's “top-level” because it imports all other modules that the program needs. Sometimes “top-level code” is called an entry point to the application.


1 Answers

The common usage is to always declare functions (and/or classes) in a module that can be used by other modules and to add at the end a if __name__ == '__main__': test to directly exec something if the script is called directly.

In your example, it would give:

# morning.py
def morning_func():
   print 'Good morning'


if __name__ == '__main__':
    # call morning func
    morning_func()

That way, you can execute it simply as python morning.py or include it in other Python files to call morning_func from there

like image 173
Serge Ballesta Avatar answered Sep 28 '22 08:09

Serge Ballesta