问题:从另一个脚本调用一个脚本的最佳方法是什么?
我有一个名为test1.py的脚本,该脚本不在模块中。它只包含应在脚本本身运行时执行的代码。没有函数,类,方法等。我有另一个作为服务运行的脚本。我想从作为服务运行的脚本中调用test1.py。
例如:
文件test1.py
print "I am a test"
print "see! I do nothing productive."
文件service.py
# Lots of stuff here
test1.py # do whatever is in test1.py
我知道一种方法是打开文件,读取内容并进行基本评估。我假设有一种更好的方法。或者至少我希望如此。
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 eval’ing it. I’m assuming there’s a better way of doing this. Or at least I hope so.
回答 0
这样做的通常方法如下。
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()
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()
回答 1
这可能在Python 2中使用
execfile("test2.py")
如果对您而言很重要,请参阅有关命名空间处理的文档。
在Python 3中,可以使用(感谢@fantastory)
exec(open("test2.py").read())
但是,您应该考虑使用其他方法。您的想法(据我所见)看起来不太干净。
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.
回答 2
另一种方式:
文件test1.py:
print "test1.py"
文件service.py:
import subprocess
subprocess.call("test1.py", shell=True)
该方法的优点是您不必编辑现有的Python脚本即可将其所有代码放入子例程中。
文档:Python 2,Python 3
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
回答 3
如果您希望test1.py保持可执行性,并且具有与在service.py内部调用时相同的功能,请执行以下操作:
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
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
回答 4
import os
os.system("python myOtherScript.py arg1 arg2 arg3")
使用os,您可以直接拨打终端电话。如果您想更具体一些,可以将输入字符串与局部变量连接在一起,即。
command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)
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)
回答 5
您不应该这样做。相反,请执行以下操作:
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()
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()
回答 6
使用import test1
的第一个用途-它会执行脚本。对于以后的调用,请将脚本视为导入的模块,然后调用该reload(test1)
方法。
当reload(module)
被执行:
- 重新编译Python模块的代码并重新执行模块级代码,从而定义了一组新对象,这些对象绑定到模块字典中的名称。扩展模块的init函数未调用
一个简单的检查sys.modules
可用于调用适当的操作。要始终将脚本名称引用为字符串('test1'
),请使用内置的‘ import()’。
import sys
if sys.modules.has_key['test1']:
reload(sys.modules['test1'])
else:
__import__('test1')
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')
回答 7
我更喜欢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')
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')
回答 8
为什么不仅仅导入test1?每个python脚本都是一个模块。更好的方法是在test1.py中具有main / run等功能,导入test1并运行test1.main()。或者,您可以将test1.py作为子进程执行。
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.
回答 9
如前所述,这runpy
是从当前脚本运行其他脚本或模块的一种好方法。
顺便说一句,跟踪器或调试器执行此操作非常普遍,在这种情况下,直接导入文件或在子进程中运行文件之类的方法通常不起作用。
还需要注意使用它exec
来运行代码。您必须提供适当的信息run_globals
以避免导入错误或其他问题。runpy._run_code
有关详情,请参阅。
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.
回答 10
这是一个带subprocess
库的示例:
import subprocess
python_version = '3'
path_to_run = './'
py_name = '__main__.py'
# args = [f"python{python_version}", f"{path_to_run}{py_name}"] # Avaible 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_)
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}"] # Avaible 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_)
回答 11
这个过程有些不合常规,但可以在所有python版本中使用,
假设您要在“ if”条件下执行名为“ recommend.py”的脚本,然后使用,
if condition:
import recommend
技术不同,但是有效!
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!