PYinstaller doesn't convert working python code into working exe - python

I'm trying to get a code scheduled in windows:
import requests
from datetime import date
import pandas as pd
import sqlalchemy
from sqlalchemy import create_engine
server= 'xxxxx'
database='xxxxx'
driver_sql= 'ODBC Driver 17 for SQL Server'
database_con= f'mssql://#{server}/{database}?driver={driver_sql}'
engine= sqlalchemy.create_engine(database_con)
connection = engine.connect()
adr='https://api.swaggystocks.com/wsb/sentiment/ticker'
r = requests.get(adr)
json = r.json()
pdbasses= pd.DataFrame(json["data"])
pdbasses["timestamp"] = pd.to_datetime("today")
pdbasses["timestamp"] = pdbasses["timestamp"].dt.strftime("%Y-%m-%d")
pdbasses.to_sql("swaggy", connection, if_exists='append',index=False)
direct =r'D:\SQL\getdatafromhere\file'+str(date.today())+".csv"
pdbasses.to_csv(direct, index=False)
the problem is, when I put it through pyinstaller it says I'm missing packages that I can't even install via pip MySQLdb,Psycob2 etc.
Then when the exe file gets put out, I run it and it just blips for a second and doesn't do anything. The code works in PyCharm. I tried running pyinstaller through pycharm, but I get a Linux exe file/spec file. I tried converting that one to an exe file, but still doens't work.
Thank you for your time

Related

Connect to JDBC python

I am try to connect to my gaussdb or even postgressql using in python jaydebeapi from linux
and i keep get error
Class name not found
I copy my jar file to /usr/lib/jvm/java-11-openjdk-amd46/lib/com.driver.jar
is there something else ?
‘’’
import jaydebeapi
import sys
jaydebeapi.connect("com.gauss.Driver",
url, [username, password], "./file-jdbc.jar")
Erorr Class com.gauss.driver not found
‘’’
You can try to explicitly start a JVM and pass it the fullpath of your driver jar file:
import jaydebeapi
import jpype
jpype.startJVM(jpype.getDefaultJVMPath(),
f"-Djava.class.path=/usr/lib/jvm/java-11-openjdk-amd46/lib/com.driver.jar")
jaydebeapi.connect("com.gauss.Driver", url, [username, password], "/usr/lib/jvm/java-11-openjdk-amd46/lib/")
If you're using postgresSQL databases I would also suggest you to take a look to the psycopg library:
https://pypi.org/project/psycopg/
https://www.geeksforgeeks.org/introduction-to-psycopg2-module-in-python/

running a python exe without a command line and getting the hwid

So ive been trying to get the hwid of a device with a app im making however i cant seem to get the hwid when compiled without a command line.
import subprocess
import PySimpleGUI as sg
import os
a = subprocess.run("wmic csproduct get uuid",capture_output=True,text=True)
x = str(a.stdout).rstrip()
x = x.splitlines()
print(x[2])
sg.popup(x[2])
#wmic csproduct get uuid
The code works perfectly in vscode (also im on python 3.9 if that matters).

Running Python Script consistently from VBA

I have VBA code calling a Python script that works on my PC.
The Python code uses SQL Alchemy to create an Engine, connects to a database, binds the session and retrieve data using a SELECT * FROM basic query. After it reads it, the data is sent to an xlsx file.
Python code with some minor changes for security reasons:
# import dependencies
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
import pandas as pd
import os
import cx_Oracle
# Creating engine connection
engine = create_engine('oracle://user:pw#IP:Port/Schema')
# Binding session
session = Session(bind=engine)
# Indicating path for Oracle client 64bits
lib_dir = r"Full_Path\instantclient_19_9"
try:
cx_Oracle.init_oracle_client(lib_dir=lib_dir)
except Exception as err:
print("Error connecting: cx_Oracle.init_oracle_client()")
print(err);
sys.exit(1);
# read sql a run query
data = pd.read_sql("SELECT * FROM Schema.V_FLUJOS_SOLICITADOS", engine)
# save path
path = r'Another_Full_Path'
# save dataframe into csv
data.to_excel(os.path.join(path, r'Flow extraction.xlsx'), index = False)
For this code, I need to tell Python where to find the Oracle client of 64 bits because my company has its database connected to a PowerBuilder program that can only use 32 bit, so I just can't change the installation, that's why I re-route.
VBA code:
Sub runScript()
Application.ScreenUpdating = False
teoricos = ThisWorkbook.Name
Dim Ret_Val
user = Environ("UserName")
Select Case user
Case "USER1"
python_route = "C:\Users\USER1\Anaconda3\python.exe"
Case "USER2"
python_route = "C:\Users\USER2\Anaconda3\python.exe"
End Select
args = """Full_path\V_FLUJOS_SOLICITADOS.py"""
Ret_Val = Shell(python_route & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub
The code works on my PC (User 1), but it doesn't on my partner's PC.
What I've done so far:
Installed cx_Oracle on her machine
Tested the whole code on Jupyter Notebook of her machine and it worked
Tested full access to all paths
Activated the Microsoft Shell Reference in VBA
The VBA code on her PC runs, but it just opens the command window really fast and it closes.
On my PC it takes from 3 to 5 seconds to do the whole thing, so I can see the CMD for just a bit there (and also check that the file updated which is the most clear indicator that it worked).

How to run python program automatically even if system restarted

I want to run my python API continuously (means program API will all-time active if call then it work) even if a system restarts my python API automatically restart.
I have API URL: http://localhost:8002/city_id_pred?id=1,2 through this URL calling python API.
Program:
import web
import pyodbc
import re
import numpy as np
#from wordcloud import WordCloud, STOPWORDS
from collections import Counter
from sklearn.externals import joblib
import pandas as pd
cnxn = pyodbc.connect('')
cursor = cnxn.cursor()
urls = (
'/city_id_pred?', 'Predict'
#'/', 'MyApplication'
)
class Predict(web.application):
def run(self, port=8080, *middleware):
func = self.wsgifunc(*middleware)
return web.httpserver.runsimple(func, ('0.0.0.0', port))
print("Start class...")
def GET(self):
#here prediction model
if __name__ == "__main__":
app = Predict(urls, globals())
app.run(port=8002)
Please suggest
Actually, I want to run on window server but currently using in windows OS.
As #Mubarak said, you basically want to convert it to a .exe and then add that .exe to startup.
I would recommend that you do this by using PyInstaller and then following this tutorial on how to add that .exe to your startup.
Following step will help you:
Make your python code like example.py
Convert example.py to example.exe file by using auto-py-to-exe https://pypi.org/project/auto-py-to-exe/
Open Task Schedular in your window system
Create Task->Gentral Tab ->Give Name,Location
Trigger Tab->Bigin the Task->On Startup
Hope this helps
Following given steps,.
1.Convert your python file to .exe format(https://pypi.org/project/auto-py-to-exe/)
Make simple batch file to run the .exe file which your python file.
#echo off
cd "C:\Program Files\Google\Chrome\Application\"
Start chrome.exe
start – "C:\Program Files\Microsoft Office\Office15\WINWORD.EXE"
"C:\Work\MUO\How to Batch Rename.docx"
cd "C:\Program Files (x86)\VMware\VMware Player"
start vmplayer.exe
exit
Hope your understood,....

Pyinstaller: Creating an Executable with Several Dependencies - "TypeError"

I have a fairly large wx application I have built and would like to compile it into a executable file. I have done this before, however, the process has become more complicated because I am working with several other dependencies (packages) and my program is composed of multiple .py files. Before I post the code, I'll describe the initial error message.
Error Message
I navigate to the directory where all my script files are saved and execute the following command in the prompt (cmd) window:
pyinstaller -F AMI_GUI.py
Pyinstaller initially runs okay however at the end of process I get this error:
TypeError: iteration over non-sequence
I have posted a screen shot to better show this error.
What is interesting is what happens next, I try running the same command again, 'pyinstaller -F AMI_GUI.py'. But this time the error does not occur, instead the process finishes and in my dist directory my executable has been created. I am also able to run the executable.
Has anyone ran into this problem before when compiling applications using pyinstaller? I have not done extensive testing on the executable file yet, but I am worried in trusting it because pyinstaller process failed on the first time.
I have posted part of my code which shows the dependencies and some of my code:
AMI_GUI.py
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float, UnicodeText, VARCHAR, NVARCHAR, TEXT, DATE, distinct, ForeignKey, Table,or_,and_
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
import math
import wx
import wx.lib.mixins.listctrl as listmix
from ObjectListView import ObjectListView, ColumnDefn
from ObjectListView import EVT_CELL_EDIT_STARTING
from ObjectListView import EVT_CELL_EDIT_FINISHING
import os
import time
from wigets import File_Manager,Date_Filter,Log_In,EVT_LOGIN
from AMI_component import engine
from AMI_component import Exception,Meter,Transformer,except_heading,meter_heading
import csv
## Link to Database
Session = sessionmaker( bind=engine ) ## Import the database engine from component file
session = Session() ## Create session to database
AMI_components.py
import os,math,random,string,operator,logging,csv
from itertools import count
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float, UnicodeText, VARCHAR, NVARCHAR, TEXT, DATE, distinct, ForeignKey, Table
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from AMI_subroutine import getFiles,incident_filt,getDB,get_manf,dayMonth,check_voltage,violation_filt,rec,get_dateTime
admin_dir = "C:\project\AMI"
# print os.getcwd()
os.chdir(admin_dir)
engine = create_engine("sqlite:///./AMI_case.db", #"oracle://rai:raisys#njnwkora18_oraa.db.pseg.com",
echo=False)
Session = sessionmaker( bind=engine )
session = Session()
Not sure if this code will help, but it does show how what import statements I have used...the some of the main file that I am running with the pyinstall command is AMI_GUI.py.
did a bit of googling, it definitely looks like a pyinstaller bug.
See:
https://groups.google.com/forum/#!topic/pyinstaller/lDCzhTS4Apo
https://github.com/pyinstaller/pyinstaller/issues/964

Categories