【发布时间】:2016-05-23 10:47:29
【问题描述】:
就像我们有 source() 函数在 R studio 的另一个 R 程序中执行 R 程序一样,我如何在另一个 python 程序中执行 python 程序?
【问题讨论】:
-
这个问题提供了一个相关的方法:What is an alternative to execfile in Python 3?
就像我们有 source() 函数在 R studio 的另一个 R 程序中执行 R 程序一样,我如何在另一个 python 程序中执行 python 程序?
【问题讨论】:
给定 2 个 python 脚本:first.py 和 second.py,从第二个开始执行第一个的通常方法是:
first.py:
def func1():
print 'inside func1 in first.py'
if __name__ == '__main__':
# first.py executed as a script
func1()
second.py:
import first
def second_func():
print 'inside second_func in second.py'
if __name__ == '__main__':
# second.py executed as a script
second_func()
first.func1() # executing a function from first.py
编辑:
execfile("second.py")(尽管它仅在调用命名空间内)。os.system,如下所示:os.system("second.py")。【讨论】:
execfile 与R 的source 最相似
source() 在 R 中所做的)。 This question 也很有帮助。
runfile() @package 以便包含的脚本在其自己的命名空间中运行。在我的场景中,这个特性特别重要,因为从包含的脚本中我需要访问 __file__ 属性,当使用 execfile() 时,该属性解析为 calling 脚本的文件名! (对我没用,因为在包含的脚本中,我需要检索它的目录位置)
如果您习惯直接从 GitHub 采购,您可以使用 requests 包通过 http get 下载原始 *.py 文件,然后执行该文件。
import requests
exec(requests.get('http://github.myorg.net/raw/repo/directory/file.py').text)
免责声明:我是学习 Python 的 R 用户,因此这可能违反了一些 Python 最佳实践
【讨论】: