0

How to execute Python3 code located remotely - e.g. github?

script_url = "https://gist.githubusercontent.com/geotheory/c874b88e712006802114a50d08c15c46/raw/1f218c0f4aa26b0596d9ef3b67005f7d4a9c8e99/python-test.py"
exec(open(script_url).read())
FileNotFoundError: [Errno 2] No such file or directory: 'https://gist.githubusercontent.com/geotheory/c874b88e712006802114a50d08c15c46/raw/1f218c0f4aa26b0596d9ef3b67005f7d4a9c8e99/python-test.py'

If there's a question already on this I'll happily delete this one, but I've not found anything.

geotheory
  • 22,624
  • 29
  • 119
  • 196
  • 2
    [`open`](https://docs.python.org/3/library/functions.html#open) only applies to files that exists on your system's filesystem. The easiest way is to [download the file](https://stackoverflow.com/questions/7243750/download-file-from-web-in-python-3) and then [execute it within Python](https://stackoverflow.com/questions/1027714/how-to-execute-a-file-within-the-python-interpreter). – metatoaster Feb 04 '19 at 10:06
  • 1
    this is insecure to do such things, to be honest – Azat Ibrakov Feb 04 '19 at 10:07
  • 1
    Ah cracked it `import urllib.request` then `exec(urllib.request.urlopen(script_url).read())` – geotheory Feb 04 '19 at 10:07
  • since `script_url` is not a valid filesystem path, it will give that error. – Asif Mohammed Feb 04 '19 at 10:09
  • @AzatIbrakov Assuming the URL points to safe code, is the risk any different to downloading the script and executing it locally? – geotheory Feb 04 '19 at 10:12

1 Answers1

2

You can do like below

import urllib

script_url = "https://gist.githubusercontent.com/geotheory/c874b88e712006802114a50d08c15c46/raw/1f218c0f4aa26b0596d9ef3b67005f7d4a9c8e99/python-test.py"
f = urllib.urlopen(script_url)
data = f.read()
exec(data)
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62