python import another python script not working - python

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.

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

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

Related

Import an LSDYAN deck in ANSA with script

I want to do a script in ANSA for importing a LS DYNA deck. I am only getting the output message "Code generation completed" but it doesn't import anything. Here is the line I am using:
PYTHON script
import os
import ansa
from ansa import base
from ansa import constants
from ansa import utils
def main():
deck=constants.LSDYNA
base.InputLSDyna(filename="C:/Documents/Model_test.k", nodes_id="offset", elements_id="offset", properties_id="offset", materials_id="offset", sets_id="offset", model_action="new_model_in_active_window", version="971r10")
if __name__ == '__main__':
main()
Can anybody help please?
Thank you

Importing modules from parent folder does not work when running flask app

I am trying to import module from file in my parent directory but is not working
Here is how my directory looks like :
Here is how my main.py file looks like :
import sys
path_modules="./Utils"
sys.path.append(path_modules)
from functools import lru_cache
from flask import Flask, render_template, request
import Utils.HardSoftClassifier as cl
import Utils.prediction_utils as ut
import Utils.DataPrepper_reg as prep
app = Flask(__name__)
#app.route('/')
#app.route('/index')
def index():
return render_template('index.html')
#app.route('/viz')
def viz():
return render_template('viz.html')
if __name__=="__main__":
# import os
# os.system("start microsoft-edge:http:\\localhost:5000/")
app.run(debug=True)
Here is my flaks output :
In order to make a package importable, it must have an (optionally empty) __init__.py file in its root. So first create an empty __init__.py file in the Utils directory.
Furthermore, you don't have to alter the import path, since you start the Flask app from the Clean_code, the simple relative importing will work. So the first three line can be removed from main.py.

Python Tkinter with Flask API and Subprocess

Could I run a function from another python file inside subprocess?
I use pyinstaller to convert the tkinter to an executable file. As much as possible I would like to deploy/run the .exe file to another computer without installing python.
#gui.py
from tkinter import *
import os
import subprocess
root = Tk()
root.geometry("300x150")
def backendStart():
subprocess.Popen(["test.py"], shell=True)
label = Label(root, text="Connection String", fg="grey", font=("Helvetica", 15, "bold"))
label.pack(pady=(0,3))
root.after_idle(backendStart)
root.mainloop()
Here is my sample app.py
from flask import Flask, jsonify
from flask_restful import Api, Resource
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import random
from connection import cursor
app = Flask(__name__)
app.config["DEBUG"] = True
api = Api(app)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*")
#socketio.on("connect")
def ClientConnection():
print("Client is Connected")
#socketio.on("realtime", namespace="/sample-socket")
def RealTimeData():
while True:
num = random.randint(1, 100)
emit("data", {"random": num})
socketio.sleep(1)
#socketio.on("disconnect")
def ClientDisconnected():
print("client has disconnected")
class HomePage(Resource):
def get(self):
return jsonify(msg="hello world")
api.add_resource(HomePage, "/")
if __name__ == '__main__':
socketio.run(app, host="192.168.0.109", port=5000)
Currently I made a .spec file for configurating the names, logo, and files/libs included. The .exe file work as long as I pasted the app.py inside the build folder along with the connection.py for the database.
But with this set up I do need to install python along with the libraries I used for the app.py and connection.py
Could I run a function from another
python file inside subprocess?
you can use multiprocessing.Process()
Edit:
For an expert's answer, see here
Alternate solution:
Lets say you want to run app.exe (which is app.py), you can pack all of them into one folder (--onedir) and put those exe's and pyd's subfolders.... together, like
gui
----flask (and other folders)
----*.pyd
----app.exe
----gui.exe
----python39.dll
you will need a custom spec file to do that.
see https://pyinstaller.readthedocs.io/en/stable/spec-files.html#multipackage-bundles

Importing values in config.py

I wanted to mix a config.py approach and ConfigParser to set some default values in config.py which could be overridden by the user in its root folder:
import ConfigParser
import os
CACHE_FOLDER = 'cache'
CSV_FOLDER = 'csv'
def main():
cp = ConfigParser.ConfigParser()
cp.readfp(open('defaults.cfg'))
cp.read(os.path.expanduser('~/.python-tools.cfg'))
CACHE_FOLDER = cp.get('folders', 'cache_folder')
CSV_FOLDER = cp.get('folders', 'csv_folder')
if __name__ == '__main__':
main()
When running this module I can see the value of CACHE_FOLDER being changed. However when in another module I do the following:
import config
def main()
print config.CACHE_FOLDER
This will print the original value of the variable ('cache').
Am I doing something wrong ?
The main function in the code you show only gets run when that module is run as a script (due to the if __name__ == '__main__' block). If you want that turn run any time the module is loaded, you should get rid of that restriction. If there's extra code that actually does something useful in the main function, in addition to setting up the configuration, you might want to split that part out from the setup code:
def setup():
# the configuration stuff from main in the question
def main():
# other stuff to be done when run as a script
setup() # called unconditionally, so it will run if you import this module
if __name__ == "__main__":
main() # this is called only when the module is run as a script

How to run multiple test case from python nose test

I am a newbie in process of learning python and currently working on a automation project.
And i have N numbers of testcase which needs to be run on reading material people suggest me to use nosetest.
What is the way to run multiple testcase using nosetest?
And is the correct approach doing it:
import threading
import time
import logging
import GLOBAL
import os
from EPP import EPP
import Queue
import unittest
global EPP_Queue
from test1 import test1
from test2 import test2
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
class all_test(threading.Thread,unittest.TestCase):
def cleanup():
if os.path.exists("/dev/epp_dev"):
os.unlink("/dev/epp_dev")
print "starts here"
server_ip ='192.168.10.15'
EppQueue = Queue.Queue(1)
EPP = threading.Thread(name='EPP', target=EPP,
args=('192.168.10.125',54321,'/dev/ttyS17',
EppQueue,))
EPP.setDaemon(True)
EPP.start()
time.sleep(5)
suite1 = unittest.TestLoader().loadTestsFromTestCase(test1)
suite2 = unittest.TestLoader().loadTestsFromTestCase(test2)
return unittest.TestSuite([suite1, suite2])
print "final"
raw_input("keyy")
def main():
unittest.main()
if __name__ == '__main__':
main()
Read
http://ivory.idyll.org/articles/nose-intro.html.
Download the package
http://darcs.idyll.org/~t/projects/nose-demo.tar.gz
Follow the instructions provided in the first link.
nosetest, when run from command line like 'nosetest' or 'nosetest-2.6' will recursively hunt for tests in the directory you execute it in.
So if you have a directory holding N tests, just execute it in that directory. They will all be executed.

Categories

Resources