EXE file for python scripts - windows

i am using python 2.7 and py2exe to try and make an exe file for my script. but it is not going so well.. my file works perfectly until I add the py2exe commands what am I doin wrong here? I need to know how to write the setup function and call it so that python knows to create and EXE file not just a compiled .py. Also this is attempted using a windows operating system.
from time import strftime
import os.path
# setup.py
import py2exe
setup(console=["LogFile.py"])
def main():
getTime()
def getTime():
time = strftime("%Y-%m-%d %I:%M:%S")
printTime(time)
def printTime(time):
savePath = "C:\Users\Nicholas\Documents"
logFile = "LogInLog.txt"
files = open(os.path.join(savePath, logFile), "a+")
openPosition = files.tell()
files.write("A LogIn occured.")
files.write(time)
files.seek(openPosition)
print(files.read())
files.close()
main()

It doesn't work that way
First, remove the setup line from your script. The setup script is a different script. Your script, fixed:
from time import strftime
import os.path
def main():
getTime()
def getTime():
time = strftime("%Y-%m-%d %I:%M:%S")
printTime(time)
def printTime(time):
savePath = r"C:\Users\Nicholas\Documents"
logFile = "LogInLog.txt"
files = open(os.path.join(savePath, logFile), "a+")
openPosition = files.tell()
files.write("A LogIn occured.")
files.write(time)
files.seek(openPosition)
print(files.read())
files.close()
Then create a file called setup.py
import py2exe
from distutils.core import setup
setup(console=["LogFile.py"])
Then type (in a command prompt, not from within python interpreter):
python setup.py py2exe
it creates the executable & aux files in dist subdir
After that go to dist
C:\DATA\jff\data\python\stackoverflow\dist>LogFile.exe
Traceback (most recent call last):
File "LogFile.py", line 25, in <module>
File "LogFile.py", line 6, in main
File "LogFile.py", line 10, in getTime
File "LogFile.py", line 15, in printTime
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Nicholas\\Documents\\LogInLog.txt'
crashing, normal I don't have your directories: it works!!

Look at this py2exe Tutorial.
Your mistakes are:
1. Missed from distutils.core import setup
2. Did not make a new file to use py2exe.
You need:
1. Remove import py2exeand setup(console=["LogFile.py"])
2. create new file "psetup.py", with code bellow:
from distutils.core import setup
import py2exe
setup(console=["your_code_name.py"])

Related

How can I save an animation from matplotlib as a mp4 video file? [duplicate]

enter code here
# -*- coding: utf-8 -*-
import math
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig1=plt.figure()
ax=plt.axes(xlim=(-10,10), ylim=(-10,10))
line,=ax.plot([],[],lw=1)
"""def init ():
line.set_data([],[])
return line,"""
dt=0.001
X=[]
Y=[]
r=float(input("Enter the radius :: "))
w=float(input("Enter angular frequency :: "))
def run(data):
t=0
while w*t<=2*math.pi:
x=r*math.cos(w*t)
y=r*math.sin(w*t)
X.append(x)
Y.append(y)
t=t+dt
line.set_data(X,Y)
return line,
line,=ax.plot(X,Y,lw=2)
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
anim=animation.FuncAnimation(fig1,run,frames=200,interval=20,blit=True)
anim.save('amim.mp4',writer=writer)
The error message shown is ::
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/tathagata/anaconda3/lib/python3.4/site- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "/home/tathagata/anaconda3/lib/python3.4/site- packages/spyderlib/widgets/externalshell/sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "/home/tathagata/Documents/Python scripts/circleamim.py", line 35, in <module>
FFMpegWriter = animation.writers['ffmpeg']
File "/home/tathagata/anaconda3/lib/python3.4/site-packages/matplotlib/animation.py", line 81, in __getitem__
return self.avail[name]
KeyError: 'ffmpeg'
I use anacoda distribution and SPYDER as my IDE. I have seen the many solutions related to key errors. But the movie wont run. How can I make the movie to run? I hope there are no other logical errors.
First install ffmpeg and add path to ffmpeg
# on windows
plt.rcParams['animation.ffmpeg_path'] = 'C:\\ffmpeg\\bin\\ffmpeg.exe'
# on linux
plt.rcParams['animation.ffmpeg_path'] = u'/home/username/anaconda/envs/env_name/bin/ffmpeg'
Note for linux users: The path for ffmpeg can be found by simply using which: which ffmpeg
Also instead of
FFMpegWriter = animation.writers['ffmpeg']
writer = FFMpegWriter(fps=15, metadata=dict(artist='Me'), bitrate=1800)
I just used writer = animation.FFMpegWriter()
It seems that ffmpegis not installed on your system. Try the following code:
import matplotlib.animation as animation
print(animation.writers.list())
It will print out a list of all available MovieWriters. If ffmpegis not among it, you need to install it first from the ffmpeg homepage.
If you have Homebrew, literally just run the command
brew install ffmpeg
And Homebrew will take care of the rest (dependencies, etc). If you don't, I would recommend getting Homebrew or something like it (apt-get on Linux is built in, or an alternative on OS X would be Macports)
I have also posed with same problem(keyError: 'ffmpeg') but instead of using anakonda, I used IDLE3. So, first i checked for 'ffmpeg' in terminal it wasn't installed so installed it.
Using: sudo apt install ffmpeg
and when I run my save_animation program, it worked generating animation files in '.mpeg' format.

Ruby and/or python: write telnetdata to file

i have a telnet-server running here (from a vendor) which is implemented in a barcode reader. to get the data, i simply need to connect to the telnetserver port 23 with my telnetclient from commandline.
What i want to do is doing this with ruby or python and write the output to a file.
so whats work until now:
i can connect to the telnet-server.
import sys
import telnetlib
tn = telnetlib.Telnet("10.0.0.138")
tn.close
output = tn.read_all()
# write to a file
with open("logging.txt", "wb") as f:
f.write(output)
# Check that the file wrote correctly.
with open("logging.txt", "rb") as f:
print(f.read())
What is not working:
writing the output from the telnetserver to a textfile.
it doesnt matter for me if i do it with python or ruby, both languages are fine.
my codesample is python here. just for trying.
thanks for reading.

how to convert python code into executable file

I have a python code that run perfect now i want to convert this code into an executable file .I am using python 3.6.
Until now I was able to convert it ,and make it run but the problem is that when the user try to run the .exe file cmd window is opened.
how can I make the cmd window to be hidden OR to not show?
the code below is to create the build folder that includes the converted executable file.
setup.py
import cx_Freeze
import sys
import os
import matplotlib
#os.environ['TCL_LIBRARY'] = "C:\\LOCAL_TO_PYTHON\\Python35-32\\tcl\\tcl8.6"
#os.environ['TK_LIBRARY'] = "C:\\LOCAL_TO_PYTHON\\Python35-32\\tcl\\tk8.6"
os.environ['TCL_LIBRARY'] = "C:\\EXECUTABLE_PROGRAMS\\Python3.6\\tcl\\tcl8.6"
os.environ['TK_LIBRARY'] = "C:\\EXECUTABLE_PROGRAMS\\Python3.6\\tcl\\tk8.6"
base = None
if sys.platform == 'win32':
base='Win32GUI'
executables = [cx_Freeze.Executable("myPDFviewer.py",base=None)]
cx_Freeze.setup(
name = "this is a test",
options = {"build_exe": {"packages":["numpy"],}},
version = "0.01",
descriptions = "Trying to get this to work",
executables = executables
)
Change base=None to base="Win32GUI"

How to clear cache (or force recompilation) in numba

I have a fairly large codebase written in numba, and I have noticed that when the cache is enabled for a function calling another numba compiled function in another file, changes in the called function are not picked up when the called function is changed. The situation occurs when I have two files:
testfile2:
import numba
#numba.njit(cache=True)
def function1(x):
return x * 10
testfile:
import numba
from tests import file1
#numba.njit(cache=True)
def function2(x, y):
return y + file1.function1(x)
If in a jupyter notebook, I run the following:
# INSIDE JUPYTER NOTEBOOK
import sys
sys.path.insert(1, "path/to/files/")
from tests import testfile
testfile.function2(3, 4)
>>> 34 # good value
However, if I change then change testfile2 to the following:
import numba
#numba.njit(cache=True)
def function1(x):
return x * 1
Then I restart the jupyter notebook kernel and rerun the notebook, I get the following
import sys
sys.path.insert(1, "path/to/files/")
from tests import testfile
testfile.function2(3, 4)
>>> 34 # bad value, should be 7
Importing both files into the notebook has no effect on the bad result. Also, setting cache=False only on function1 also has no effect. What does work is setting cache=False on all njit'ted functions, then restarting the kernel, then rerunning.
I believe that LLVM is probably inlining some of the called functions and then never checking them again.
I looked in the source and discovered there is a method that returns the cache object numba.caching.NullCache(), instantiated a cache object and ran the following:
cache = numba.caching.NullCache()
cache.flush()
Unfortunately that appears to have no effect.
Is there a numba environment setting, or another way I can manually clear all cached functions within a conda env? Or am I simply doing something wrong?
I am running numba 0.33 with Anaconda Python 3.6 on Mac OS X 10.12.3.
I "solved" this with a hack solution after seeing Josh's answer, by creating a utility in the project method to kill off the cache.
There is probably a better way, but this works. I'm leaving the question open in case someone has a less hacky way of doing this.
import os
def kill_files(folder):
for the_file in os.listdir(folder):
file_path = os.path.join(folder, the_file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except Exception as e:
print("failed on filepath: %s" % file_path)
def kill_numba_cache():
root_folder = os.path.realpath(__file__ + "/../../")
for root, dirnames, filenames in os.walk(root_folder):
for dirname in dirnames:
if dirname == "__pycache__":
try:
kill_files(root + "/" + dirname)
except Exception as e:
print("failed on %s", root)
This is a bit of a hack, but it's something I've used before. If you put this function in the top-level of where your numba functions are (for this example, in testfile), it should recompile everything:
import inspect
import sys
def recompile_nb_code():
this_module = sys.modules[__name__]
module_members = inspect.getmembers(this_module)
for member_name, member in module_members:
if hasattr(member, 'recompile') and hasattr(member, 'inspect_llvm'):
member.recompile()
and then call it from your jupyter notebook when you want to force a recompile. The caveat is that it only works on files in the module where this function is located and their dependencies. There might be another way to generalize it.

Using windows command line to run python script with passing of url argument

I am writing this Python program which extracts some information from a webpage and I am required to run it using the windows command line. But I could not even print the original html page as a string. I am using Python 2.7
Here is my Python script:
#sys.py
import sys
import urllib
url = sys.argv[1]
f = urllib.urlopen(url)
print f.read()
When I try to run it from windows command line with: C...>sys.py "www.marinetraffic.com/ais/shipdetails.aspx?mmsi=311389000"
Errors appear as follows:
Traceback(most recent call last):
File "C:\...\sys.py", line 14 in <module>
f = urllib.urlopen(url)
File "C:\Python27\lib\urllib.py", line 87, in urlopen
return opener.open(url)
File "C:\Python27\lib\urllib.py", line 208, in open
return getattr(self, name)(url)
File "C:\Python27\lib\urllib.py", line 463, in open_file
return self.open_local_file(url)
File "C:\Python27\lib\urllib.py", line 87, in open_loca_file
raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] The system cannot find the path specified: 'www.marinetraffic.com\\ais\\shipdetails.aspx?mmsi=311389000'
There should not be any problem with the Python set up under the windows environment because I can still print out the sys.argv list as the arguments are passed in the command line.
Is it the problem with the 'urllib' library?
Is there any another way to run this using windows command line?
I think the problem is the way you specify your url, it needs to have the http:// part at the start.
It works for me when I type
python sys.py http://www.google.com/
but fails with
python sys.py www.google.com
(Note that I am using linux with python 2.7 but I think it may be the same problem for you)

Resources