Reputation: 261
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?
Upvotes: 8
Views: 16413
Reputation: 58
Have you tried creating a directory my_script
and then create a __init__.py
file in that directory? You can then put your entire script inside the __init__.py
file.
To run the script from your python program, you can
import my_script
my_script
Upvotes: 0
Reputation: 148965
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
Upvotes: 7
Reputation: 1985
As you said calling morning like that is messy, I Suggest import morning like this:
# main.py
from morning import morning_func as morning
then you can call morning like this:
morning()
If you wanna run morning.py
separately, as @Serge Ballesta said modify morning.py
like this:
# morning.py
def morning_func():
print 'Good morning'
if __name__ == '__main__':
morning_func()
Upvotes: 0
Reputation: 21666
Adding to above answer, the best way in this case would be to go through the original morning script line by line and wrap the actions in related functions. Refer this recipe on How to convert a Python script to module.
Upvotes: 0