0

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.

asked Sep 14, 2017 at 21:40
4
  • 1
    did you try from script1 import *? Commented Sep 14, 2017 at 21:43
  • 2
    Or changing api_call in script2 to script1.api_call? Commented Sep 14, 2017 at 21:47
  • 2
    @saniales that's a very bad practice. Commented Sep 14, 2017 at 21:51
  • yes, it was just to understand if it was an import problem, clearly the correct solution would be to import only what you need. Commented Sep 15, 2017 at 7:29

2 Answers 2

3

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

saniales
4513 silver badges15 bronze badges
answered Sep 14, 2017 at 21:47
-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

answered Sep 14, 2017 at 21:49
1
  • 1
    This syntax (from .module import ...) refers to relative import from submodules. It should be used within packages, and does not seems an appropriate solution. Same thing for __init__.py, a repertory containing this file will be recognized as a package, which is not necessary, and probably not desired here. Commented Sep 14, 2017 at 21:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.