Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of source() of R in Python

Tags:

python

execute

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?

like image 319
Devesh Avatar asked Feb 12 '16 10:02

Devesh


People also ask

Which function is equivalent to R in Python?

The pandas package for Python also has a function called apply, which is equivalent to its R counterpart; the following code illustrates how to use it.

What is a source file in Python?

Python source files are files that contain Python source code. As Python can be used as a scripting language, Python source files can be considered as scripts. PYW files are invoked on pythonw.exe instead of python.exe in order to prevent a DOS console from popping up to display the output.

Can you write R code in Python?

The RStudio IDE(opens in a new tab) is a free and open-source IDE for Python, as well as R. You can write scripts, import modules, and interactively use Python within the RStudio IDE. To get started writing Python in the RStudio IDE, go to File, New File, then Python Script.


2 Answers

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").
like image 168
Idos Avatar answered Sep 20 '22 21:09

Idos


If you're used to sourcing directly from GitHub, you can use the requests package to download the raw *.py file with an http get, and then execute the file.

import requests
exec(requests.get('http://github.myorg.net/raw/repo/directory/file.py').text)

Disclaimer: I'm an R user learning Python, so this might be violating some Python best practices

like image 43
Nadir Sidi Avatar answered Sep 23 '22 21:09

Nadir Sidi