Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to call a script from another script?

Tags:

python

I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.

For example:

File test1.py:

print "I am a test" print "see! I do nothing productive." 

File service.py:

# Lots of stuff here test1.py # do whatever is in test1.py 

I'm aware of one method which is opening the file, reading the contents, and basically evaluating it. I'm assuming there's a better way of doing this. Or at least I hope so.

like image 565
Josh Smeaton Avatar asked Jul 27 '09 06:07

Josh Smeaton


People also ask

How do you call one script from another script in Shell?

this: source /path/to/script; Or use a bash command to execute it: /bin/bash /path/to/script; The 1st and 3rd methods execute a script as another process, so variables and functions in another script will not be accessible.

How do I call a Python script?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


1 Answers

The usual way to do this is something like the following.

test1.py

def some_func():     print 'in test 1, unproductive'  if __name__ == '__main__':     # test1.py executed as script     # do something     some_func() 

service.py

import test1  def service_func():     print 'service func'  if __name__ == '__main__':     # service.py executed as script     # do something     service_func()     test1.some_func() 
like image 90
ars Avatar answered Sep 18 '22 00:09

ars