Compiled console app quits immediately when importing ConfigParser (Python 2.7.12) - python-2.7

I am very new to Python and am trying to append some functionality to an existing Python program. I want to read values from a config INI file like this:
[Admin]
AD1 = 1
AD2 = 2
RSW = 3
When I execute the following code from IDLE, it works as ist should (I already was able to read in values from the file, but deleted this part for a shorter code snippet):
#!/usr/bin/python
import ConfigParser
# buildin python libs
from time import sleep
import sys
def main():
print("Test")
sleep(2)
if __name__ == '__main__':
main()
But the compiled exe quits before printing and waiting 2 seconds. If I comment out the import of ConfigParser, exe runs fine.
This is how I compile into exe:
from distutils.core import setup
import py2exe, sys
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
zipfile = None,
console=['Test.py'],
)
What am I doing wrong? Is there maybe another way to read in a configuration in an easy way, if ConfigParser for some reason doesnt work in a compiled exe?
Thanks in advance for your help!

Related

how can I import subfolders module python to another file?

I want to access to my modules.module function A in my main , but when I do this I have an error that I cannot import that.. how can I fix it? I Have seen multiples articles but i hadnt a chance, how can I fix this error of importing modules from subfolders?
**/tool
main.py
/google
/modules
__init__.py
module.py**
ImportError: cannot import name google
main.py
#!/usr/bin/python
import sys
import core.settings
from google.modules import google
if __name__ == '__main__':
try:
core.settings.settings()
google()
except KeyboardInterrupt:
print "interrupted by user.."
except:
sys.exit()
module.py
def google():
print 'A'
the easiest way to work this out is have your main.py in your highest directory (it makes sense anyway for main to be there) and if you really want the real main to be in a sub directory have a dummy main at the top level you can call that just calls the actual main, that way python can see your entire directory tree and will know how to import any sub directory.
alternatively
you could add your parent directory to the sys.path:
parent_dir = os.path.realpath(os.path.join(os.getcwd(),'..')))
sys.path.append(parent_dir)
which will add that directory to the places python searches for when you try to import stuff.
but then you will need to keep track of how deep your main is in the directory tree and its a pretty unelegant solution in my opinion

Shebang command to call script from existing script - Python

I am running a python script on my raspberry pi, at the end of which I want to call a second python script in the same directory. I call it using the os.system() command as shown in the code snippet below but get import errors. I understand this is because the system interprets the script name as a shell command and needs to be told to run it using python, using the shebang line at the beginning of my second script.
#!/usr/bin/env python
However doing so does not solve the errors
Here is the ending snippet from the first script:
# Time to Predict E
end3 = time.time()
prediction_time = end3-start3
print ("\nPrediction time: ", prediction_time, "seconds")
i = i+1
print (i)
script = '/home/pi/piNN/exampleScript.py'
os.system('"' + script + '"')
and here is the beginning of my second script:
'#!usr/bin/env python'
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from picamera import PiCamera
import argparse
import sys
import time
import numpy as np
import tensorflow as tf
import PIL.Image as Image
Any help is greatly appreciated :)
Since you have not posted the actual errors that you get when you run your code, this is my best guess. First, ensure that exampleScript.py is executable:
chmod +x /home/pi/piNN/exampleScript.py
Second, add a missing leading slash to the shebang in exampleScript.py, i.e. change
'#!usr/bin/env python'
to
'#!/usr/bin/env python'
The setup that you have here is not ideal.
Consider simply importing your other script (make sure they are in the same directory). Importing it will result in the execution of all executable python code inside the script that is not wrapped in if __name__ == "__main__":. While on the topic, should you need to safeguard some code from being executed, place it in there.
I have 2 python file a.py and b.py and I set execute permission for b.py with.
chmod a+x b.py
Below is my sample:
a.py
#!/usr/bin/python
print 'Script a'
import os
script = './b.py'
os.system('"' + script + '"')
b.py
#!/usr/bin/python
print 'Script b'
Execute "python a.py", the result is:
Script a
Script b

Cant make multiple copies of a file using shutil python

Following is a python code snippet I am running on my server. I want to replicate a file 'n' times and save with a different name each time. However, whatever value I give for loop I always end up getting a single replica made.
import os
import time
import shutil
os.chdir(''server_directory)
src='myFile.jpg'
numberofcopies=10
for i in range(0,numberofcopies):
print "replicating {0}".format(i+1)
timestamp=int(round(time.time()))
dst='{0}.jpg'.format(timestamp)
shutil.copy2(src, dst)
Apparently using a timeout in the main thread and running the loop infinitely unless Ctrl-C interruption solved my problem.
import os
import time
import shutil
os.chdir('server_directory')
src='file to replicate.jpg'
i=0
while True:
print "replicating {0}".format(i+1)
timestamp=int(round(time.time()))
dst='{0}.jpg'.format(timestamp)
shutil.copy2(src, dst)
i=i+1
time.sleep(1)
This should replicate my file 5 times with different names.
import os
import shutil
import os
for r in range(5):
original = r'transactions.xlsx'
target = f'Newfile{r}.xlsx'
shutil.copyfile(original, target)
print (f'Action: replicating {original} as {target}')

From module import * is not importing my functions

I am trying to understand how to import code from one file to another. I have two files file1.py and file2.py. I am running code in the first file, and have many variables and functions defined in the second file. I am using from file2 import * to import the code into file1.py. I have no problem using variables defined in file2.py in file1.py, but with functions I am getting NameError: name 'myfunc' is not defined when I try to use the function in file1.py. I can fix this problem by writing from file2 import myfunc, but I thought writing * would import everything from that file. What is the difference for functions versus variables?
I have tried to recreate the setup you have described and it is working OK for me. Hopefully this will give you an idea of how to get it to work.
# file1.py #####################################
import sys
sys.path.append("/home/neko/test/")
import file2
if __name__ == "__main__":
file2.testfunc()
# file2.py ######################################
testvar = 'hello'
def testfunc(): print testvar
For this test I was using python version 2.6.6
Both file1.py and file2.py is in /home/neko/test/

ipython showing gibberish when debugging Django with Netbeans

I'm using Netbeans for coding Django. When I insert:
import ipdb; ipdb.set_trace()
Flow execution gets stopped but it shows gibberish, such as:
[1;32m/path/to/file/models.py[0m(344)[0;36macceptBid[1;34m()[0m
[1;32m 343 [1;33m [1;32mimport[0m [1;37mipdb[0m[1;33m;[0m [1;37mipdb[0m[1;33m.[0m[1;37mset_trace[0m[1;33m([0m[1;33m)[0m[1;33m[0m[0m
[0m[1;32m--> 344 [1;33m [1;32mreturn[0m [1;37mself[0m[1;33m.[0m[1;37msenderId[0m[1;33m([0m[1;33m)[0m [1;33m==[0m [1;37muser_obj[0m[1;33m.[0m[1;37mid[0m[1;33m[0m[0m
[0m[1;32m 345 [1;33m[1;33m[0m[0m
[0m
I can use next, skip and everything from pdb. But I can not see where I'm in the code, which forces me to use pdb instead of ipdb.
for me worked fine with just commenting the line and add a pass sentence in ipdb/__main__.py
from IPython.utils import io
def update_stdout():
# setup stdout to ensure output is available with nose
#THIS IS THE LINE TO COMMENT #########################
#io.stdout = sys.stdout = sys.__stdout__
#REMEMBER TO ADD pass
pass
else:
from IPython.Debugger import Pdb, BdbQuit_excepthook
from IPython.Shell import IPShell
from IPython import ipapi
These are ANSI escape codes, which are used for the text colours in ipdb's output. For some reason, the terminal you're debugging in is not accepting the codes and is printing them as text. You may be able to find a setting in NetBeans to either change what the terminal is reporting itself as, or what it actually accepts.
This is the problem:
https://github.com/gotcha/ipdb/issues/31
and you can solve it by commenting out a line in ipdb/_ _ main _ _.py
What I have done to be able to use ipdb with Django Netbeans, is disable coloring output in ipdb. There are several ways to do this. If you have installed ipdb through easy_install you can edit the code in __init__.py leaving it like:
import sys
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
from IPython import ipapi
shell = IPShell(argv=[''])
def set_trace():
Pdb("NoColor").set_trace(sys._getframe().f_back)
Also you can create yourself a hook to import ipdb without colors. I hope this helps :)