我有一个名为test1.py的脚本,它不在模块中.它只有在脚本本身运行时才能执行的代码.没有函数,类,方法等.我有另一个作为服务运行的脚本.我想从作为服务运行的脚本中调用test1.py.
例如:
print "I am a test"
print "see! I do nothing productive."
Run Code Online (Sandbox Code Playgroud)
# Lots of stuff here
test1.py # do whatever is in test1.py
Run Code Online (Sandbox Code Playgroud)
我知道一种方法是打开文件,读取内容,并基本上评估它.我假设有一个更好的方法来做到这一点.或者至少我希望如此.
ars*_*ars 259
通常的方法是执行此操作,如下所示.
test1.py
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
bal*_*pha 127
这在Python 2中可以使用
execfile("test2.py")
Run Code Online (Sandbox Code Playgroud)
有关命名空间处理的文档,如果在您的情况下很重要,请参阅.
但是,您应该考虑使用不同的方法; 你的想法(从我所看到的)看起来不是很干净.
小智 67
其他方式:
print "test1.py"
Run Code Online (Sandbox Code Playgroud)
import subprocess
subprocess.call("test1.py", shell=True)
Run Code Online (Sandbox Code Playgroud)
此方法的优点是您不必编辑现有的Python脚本以将其所有代码放入子例程.
Mic*_*der 19
如果你希望test1.py保持可执行的功能与在service.py中调用它时的功能相同,那么执行以下操作:
test1.py
def main():
print "I am a test"
print "see! I do nothing productive."
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
service.py
import test1
# lots of stuff here
test1.main() # do whatever is in test1.py
Run Code Online (Sandbox Code Playgroud)
Fla*_*vio 13
我更喜欢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')
Run Code Online (Sandbox Code Playgroud)
the*_*edz 12
你不应该这样做.相反,做:
test1.py:
def print_test():
print "I am a test"
print "see! I do nothing productive."
Run Code Online (Sandbox Code Playgroud)
service.py
#near the top
from test1 import print_test
#lots of stuff here
print_test()
Run Code Online (Sandbox Code Playgroud)
使用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')
Run Code Online (Sandbox Code Playgroud)
小智 6
import os
os.system("python myOtherScript.py arg1 arg2 arg3")
Run Code Online (Sandbox Code Playgroud)
使用操作系统,您可以直接拨打终端.如果您想要更具体,可以将输入字符串与局部变量连接起来,即.
command = 'python myOtherScript.py ' + sys.argv[1] + ' ' + sys.argv[2]
os.system(command)
Run Code Online (Sandbox Code Playgroud)
正如已经提到的,runpy
这是从当前脚本运行其他脚本或模块的好方法。
顺便说一句,跟踪器或调试器执行此操作很常见,在这种情况下,直接导入文件或在子进程中运行文件等方法通常不起作用。
使用exec
来运行代码也需要注意。您必须提供正确的信息run_globals
以避免导入错误或其他一些问题。runpy._run_code
详情请参阅。
归档时间: |
|
查看次数: |
419086 次 |
最近记录: |