简体   繁体   中英

How do I import a python file from a different server?

I am very confused because I have a python server up and running on https://python-server-password-manager.wotsitgamer.repl.co/ . On that server there is a file named "main.py". I need to link a function from that file to the local python application. I tried to use the following:

import https://python-server-password-manager.wotsitgamer.repl.co/

... but that just gives me an error.

Any help would be great.

You cannot directly import a file remotely, but you can download it then execute it by importing it.

from requests import get

# Download the file
code = get("https://python-server-password-manager.wotsitgamer.repl.co/main.py").text

# Write the data to a file
with open("main.py", "w") as f:
    f.write(code)

# Run the code
import main

Update:
As mentioned in the comments, OP wants to interact with the remote script as if it is located locally (specifically, transferal of data) . In that case, there is not really a better option than running an API on the website, or a shared database of some sort (eg, Firebase).

You can play around with Pythons ModuleFinder .

I have never done it, but this project is an example for that.

It is in my opinion a bit of an over kill, and a more trivial solution will be to fetch the files to your local machine, and import in the usual way.

Python doesn't support imports over HTTP. You'll have to somehow (there are various methods) map a virtual drive to your local computer, then add that location to sys.path so Python can locate it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM