21

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?

Idos
  • 15,053
  • 14
  • 60
  • 75
Devesh
  • 719
  • 1
  • 7
  • 13
  • This question provides a related approach to this: [What is an alternative to execfile in Python 3?](https://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3?noredirect=1&lq=1) – divibisan Mar 29 '19 at 23:45

2 Answers2

8

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").
Idos
  • 15,053
  • 14
  • 60
  • 75
  • 2
    I found the `execfile` to be most similar to R's `source` – vpipkt Feb 01 '18 at 13:58
  • I agree with vpipkt. It might not be the most Pythonic way of doing things, but sometimes I just want to execute another Python script as though it were within the first script (which is what `source()` does in R). [This question](https://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3?noredirect=1&lq=1) was also helpful. – mickey Jan 08 '19 at 16:17
  • Regarding note by @ldos on the first bullet of their edited answer: "(although it is only within the calling namespace)": to avoid this issue, we can use `runfile()` from the `sitecustomize` package so that the included script is run in its own namespace. In my scenario, this characteristic is particulary crucial because from the included script I need to access the `__file__` property which, when using `execfile()` resolves to the file name of the _calling_ script! (not useful to me, since inside the included script, I need to retrieve its directory location) – mastropi Feb 29 '20 at 16:08
1

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

Nadir Sidi
  • 1,706
  • 2
  • 9
  • 12