user2966197
user2966197

Reputation: 2981

python import another python script not working

I have two python scripts which are in the same directory(C:\\Users\\user1\\general). I want to execute a function in one script from the 2nd second script and so I am trying to import script1 in script2. Here is my script2:

import sys
sys.path.insert(0, 'C:\\Users\\user1\\general')
import script1
from flask import Flask
from flask_socketio import SocketIO, send


app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app)

@socketio.on('message')
def handleMessage(msg):
    print('Message: ' + msg)
    # script1 has function called api_call(id,message)
    messsage = api_call('user1', msg)
    send(messsage, broadcast=True)

if __name__ == '__main__':
    socketio.run(app)

Here is my script1:

import sys

def api_call(Id,message):
    # Code processing


if __name__ == '__main__':

    uId = sys.argv[0]
    message = sys.argv[1]
    api_call(userId,message)

When I execute above script2 I get NameError: name 'api_call' is not defined. It seems somehow the script1 is not getting imported and so the function is not getting through.

Note: Earlier I had tried without using sys.path.insert() and same outcome then also.

Upvotes: 0

Views: 448

Answers (2)

n3utrino
n3utrino

Reputation: 1210

Try from script1 import api_call: this would allow to import from script1 module the api_call function.

Upvotes: 3

iGiveUpLoL
iGiveUpLoL

Reputation: 1

Python 2

Create __init__.py in the same folder.

Import using following command

from script1 import api_call


Python 3

Import using following command

from .script1 import api_call

Upvotes: -1

Related Questions