Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
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.
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()
This is possible in Python 2 using
execfile("test2.py")
See the documentation for the handling of namespaces, if important in your case.
In Python 3, this is possible using (thanks to #fantastory)
exec(open("test2.py").read())
However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.
Another way:
File test1.py:
print "test1.py"
File service.py:
import subprocess
subprocess.call("test1.py", shell=True)
The advantage to this method is that you don't have to edit an existing Python script to put all its code into a subroutine.
Documentation: Python 2, Python 3
import os
os.system("python myOtherScript.py arg1 arg2 arg3")
Using os you can make calls directly to your terminal. If you want to be even more specific you can concatenate your input string with local variables, ie.
command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)
If you want test1.py to remain executable with the same functionality as when it's called inside service.py, then do something like:
test1.py
def main():
print "I am a test"
print "see! I do nothing productive."
if __name__ == "__main__":
main()
service.py
import test1
# lots of stuff here
test1.main() # do whatever is in test1.py
I prefer runpy:
#!/usr/bin/env python
# coding: utf-8
import runpy
runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')
You should not be doing this. Instead, do:
test1.py:
def print_test():
print "I am a test"
print "see! I do nothing productive."
service.py
#near the top
from test1 import print_test
#lots of stuff here
print_test()
Use import test1 for the 1st use - it will execute the script. For later invocations, treat the script as an imported module, and call the reload(test1) method.
When reload(module) is executed:
Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called
A simple check of sys.modules can be used to invoke the appropriate action. To keep referring to the script name as a string ('test1'), use the 'import()' builtin.
import sys
if sys.modules.has_key['test1']:
reload(sys.modules['test1'])
else:
__import__('test1')
As it's already mentioned, runpy is a nice way to run other scripts or modules from current script.
By the way, it's quite common for a tracer or debugger to do this, and under such circumstances methods like importing the file directly or running the file in a subprocess usually do not work.
It also needs attention to use exec to run the code. You have to provide proper run_globals to avoid import error or some other issues. Refer to runpy._run_code for details.
Why not just import test1? Every python script is a module. A better way would be to have a function e.g. main/run in test1.py, import test1 and run test1.main(). Or you can execute test1.py as a subprocess.
I found runpy standard library most convenient. Why? You have to consider case when error raised in test1.py script, and with runpy you are able to handle this in service.py code. Both traceback text (to write error in log file for future investigation) and error object (to handle error depends on its type): when with subprocess library I wasn't able to promote error object from test1.py to service.py, only traceback output.
Also, comparing to "import test1.py as a module" solution, runpy is better cause you have no need to wrap code of test1.py into def main(): function.
Piece of code as example, with traceback module to catch last error text:
import traceback
import runpy #https://www.tutorialspoint.com/locating-and-executing-python-modules-runpy
from datetime import datetime
try:
runpy.run_path("./E4P_PPP_2.py")
except Exception as e:
print("Error occurred during execution at " + str(datetime.now().date()) + " {}".format(datetime.now().time()))
print(traceback.format_exc())
print(e)
This process is somewhat un-orthodox, but would work across all python versions,
Suppose you want to execute a script named 'recommend.py' inside an 'if' condition, then use,
if condition:
import recommend
The technique is different, but works!
Add this to your python script.
import os
os.system("exec /path/to/another/script")
This executes that command as if it were typed into the shell.
An example to do it using subprocess.
from subprocess import run
import sys
run([sys.executable, 'fullpathofyourfile.py'])
This is an example with subprocess library:
import subprocess
python_version = '3'
path_to_run = './'
py_name = '__main__.py'
# args = [f"python{python_version}", f"{path_to_run}{py_name}"] # works in python3
args = ["python{}".format(python_version), "{}{}".format(path_to_run, py_name)]
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()
if not error_:
print(output)
else:
print(error_)
According to the given example, this is the best way:
# test1.py
def foo():
print("hellow")
# test2.py
from test1 import foo # might be different if in different folder.
foo()
But according to the title, using os.startfile("path") is the best way as its small and it works. This would execute the file specified. My python version is 3.x +.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
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.
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()
This is possible in Python 2 using
execfile("test2.py")
See the documentation for the handling of namespaces, if important in your case.
In Python 3, this is possible using (thanks to #fantastory)
exec(open("test2.py").read())
However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.
Another way:
File test1.py:
print "test1.py"
File service.py:
import subprocess
subprocess.call("test1.py", shell=True)
The advantage to this method is that you don't have to edit an existing Python script to put all its code into a subroutine.
Documentation: Python 2, Python 3
import os
os.system("python myOtherScript.py arg1 arg2 arg3")
Using os you can make calls directly to your terminal. If you want to be even more specific you can concatenate your input string with local variables, ie.
command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)
If you want test1.py to remain executable with the same functionality as when it's called inside service.py, then do something like:
test1.py
def main():
print "I am a test"
print "see! I do nothing productive."
if __name__ == "__main__":
main()
service.py
import test1
# lots of stuff here
test1.main() # do whatever is in test1.py
I prefer runpy:
#!/usr/bin/env python
# coding: utf-8
import runpy
runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')
You should not be doing this. Instead, do:
test1.py:
def print_test():
print "I am a test"
print "see! I do nothing productive."
service.py
#near the top
from test1 import print_test
#lots of stuff here
print_test()
Use import test1 for the 1st use - it will execute the script. For later invocations, treat the script as an imported module, and call the reload(test1) method.
When reload(module) is executed:
Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called
A simple check of sys.modules can be used to invoke the appropriate action. To keep referring to the script name as a string ('test1'), use the 'import()' builtin.
import sys
if sys.modules.has_key['test1']:
reload(sys.modules['test1'])
else:
__import__('test1')
As it's already mentioned, runpy is a nice way to run other scripts or modules from current script.
By the way, it's quite common for a tracer or debugger to do this, and under such circumstances methods like importing the file directly or running the file in a subprocess usually do not work.
It also needs attention to use exec to run the code. You have to provide proper run_globals to avoid import error or some other issues. Refer to runpy._run_code for details.
Why not just import test1? Every python script is a module. A better way would be to have a function e.g. main/run in test1.py, import test1 and run test1.main(). Or you can execute test1.py as a subprocess.
I found runpy standard library most convenient. Why? You have to consider case when error raised in test1.py script, and with runpy you are able to handle this in service.py code. Both traceback text (to write error in log file for future investigation) and error object (to handle error depends on its type): when with subprocess library I wasn't able to promote error object from test1.py to service.py, only traceback output.
Also, comparing to "import test1.py as a module" solution, runpy is better cause you have no need to wrap code of test1.py into def main(): function.
Piece of code as example, with traceback module to catch last error text:
import traceback
import runpy #https://www.tutorialspoint.com/locating-and-executing-python-modules-runpy
from datetime import datetime
try:
runpy.run_path("./E4P_PPP_2.py")
except Exception as e:
print("Error occurred during execution at " + str(datetime.now().date()) + " {}".format(datetime.now().time()))
print(traceback.format_exc())
print(e)
This process is somewhat un-orthodox, but would work across all python versions,
Suppose you want to execute a script named 'recommend.py' inside an 'if' condition, then use,
if condition:
import recommend
The technique is different, but works!
Add this to your python script.
import os
os.system("exec /path/to/another/script")
This executes that command as if it were typed into the shell.
An example to do it using subprocess.
from subprocess import run
import sys
run([sys.executable, 'fullpathofyourfile.py'])
This is an example with subprocess library:
import subprocess
python_version = '3'
path_to_run = './'
py_name = '__main__.py'
# args = [f"python{python_version}", f"{path_to_run}{py_name}"] # works in python3
args = ["python{}".format(python_version), "{}{}".format(path_to_run, py_name)]
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()
if not error_:
print(output)
else:
print(error_)
According to the given example, this is the best way:
# test1.py
def foo():
print("hellow")
# test2.py
from test1 import foo # might be different if in different folder.
foo()
But according to the title, using os.startfile("path") is the best way as its small and it works. This would execute the file specified. My python version is 3.x +.
This question already has answers here:
Why is Python running my module when I import it, and how do I stop it?
(12 answers)
Closed 5 years ago.
I have two files, file1 and file2.
files 2 is this:
print "Why is this printing"
var = 7
file 1 is this:
from file2 import var
print var
When I run this code, it outputs the following:
Why is this printing
7
Is there a way I can obtain var from file2 without running the code above the declaration of var?
If you don't want code to run when a module is imported, put it in a function:
def question():
print("Why is this printing")
If you want the function to run when the module is passed to the python interpreter on the command line, put it in a conditional expression block:
if __name__ == '__main__':
question()
e.g.
c:/> python file2.py
Why is this printing
You can use standard
if __name__ == "__main__":
guard to protect some lines from executing on importing. This condition is satisfied only if you run that particular file, not import it.
This question already has answers here:
How do I run Python code from Sublime Text 2?
(16 answers)
Closed 6 years ago.
I am newbie, pls don't be to harsh with me.
I am trying to setup Sublime Text with Python (for next Semester). Before that I used Haskell in SublimeText, where I could run my skript with "ctrl+b" in Sublime.
When I try doing the same with a file named "test.py".
def add(a,b):
return a+b
main = print(add(2,3))
I get the error-message:
/home/nayooti/Desktop/test.py:1:1:
**Parse error: naked expression at top level**
[Finished in 0.2s with exit code 1]
[shell_cmd: runhaskell "/home/nayooti/Desktop/test.py"]
[dir: /home/nayooti/Desktop]
[path: /usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games]
The "naked expression at top level"-part looks familiar, since it is very Haskell specific. Indeed, when I search the Web for exactly this message, it brings me to Haskell related stuff only. So apparently Sublime or the compiler thinks, I am trying to run a Haskell-script, even though I named the file ~.py .
For these, who are not familiar with Haskell and Python:
you can usually run a script by:
Python: main = print(method(x,y))
Haskell: main = print(function x y)
I am using Ubuntu 12.04. What am I doing wrong here? Help is very appreciated. Tx.
Go to Tools -> Build System and make sure that Python is selected. Also, that is not how you write main in Python, it should be more like
def add(a, b):
return a + b
def main():
print(add(2, 3))
if __name__ == '__main__':
main()
When you write
main = print(add(2, 3))
And load your script, that line gets executed since it is an assignment, much the same if I did
a = 1
Or
a = print(add(2, 3))
There is nothing special about the name main in Python. You still see your output because print has side effects, but rather than defining main you are just executing a script. The difference comes in if you were to try
add.py:
def add(a, b):
return a + b
main = print(add(2, 3))
subtract.py:
from add import add
def subtract(a, b):
return add(a, -b)
If you ran python subtract.py, you would still see 5 printed to the screen, even though there is no main defined in subtract.py. Obviously, this is not desired behavior, your main function in add.py should not be executing if you did not run it as the main script. When you run a Python script directly as python scriptname.py, there is a variable set global to that file called __name__ that gets assigned the string "__main__". If you import it, then __name__ is set to its qualified module name, something like "scriptname". This gives you the ability to define different behavior if the file is executed compared to if the file is imported by another script.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does <if name==“main”:> do?
I have wrote scripts in Python for quite a while now and I study more of Python as I need it. When reading other people's code I meet if name == "__main__": construct quite often.
What is it good for?
This allows you to use the same file both as a library (by importing it) or as the starting point for an application.
For example, consider the following file:
# hello.py
def hello(to=__name__):
return "hello, %s" % to
if __name__ == "__main__":
print hello("world")
You can use that code in two ways. For one, you can write a program that imports it. If you import the library, __name__ will be the name of the library and thus the check will fail, and the code will not execute (which is the desired behavior):
#program.py
from hello import hello # this won't cause anything to print
print hello("world")
If you don't want to write this second file, you can directly run your code from the command line with something like:
$ python hello.py
hello, __main__
This behavior all depends on the special variable __name__ which python will set based on whether the library is imported or run directly by the interpreter. If run directly it will be set to __main__. If imported it will be set to the library name (in this case, hello).
Often this construct is used to add unit tests to your code. This way, when you write a library you can embed the testing code right in the file without worrying that it will get executed when the library is used in the normal way. When you want to test the library, you don't need any framework because you can just run the library as if it were a program.
See also __main__ in the python documentation (though it's remarkably sparse)
Basically,
There's a distinction between the "main" script file and external files which were imported or referenced in another way. If the script is the "main" script then the special variable __name__ will equal "__main__".
You can use this to protect the "execution" code from the classes and variables the script has. This enables you to import a script and use classes and variables without actually running that script's main code if it has any.
See also: What does if name == “main”: do?