等价于Python中R的source() [英] Equivalent of source() of R in Python

查看:131
本文介绍了等价于Python中R的source()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我们具有source()函数一样,可以在R studio中的另一个R程序中执行R程序,如何在另一个python程序中执行python程序?

解决方案

给出2个python脚本:first.pysecond.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").

Like we have source() function to execute a R program in another R program in R studio, how do I execute a python program in another python program?

解决方案

Given 2 python scripts: first.py and second.py, the usual way to execute the first from the second is something in the lines of:

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

Edits:

  • You could also go for the simple execfile("second.py") if you wish (although it is only within the calling namespace).
  • And a final option is using os.system like so:
    os.system("second.py").

这篇关于等价于Python中R的source()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆