python tkinter using variables across files,? - python-2.7

I have been playing with Tkinter in Python 2.7, and just ran across something that SHOULD be a bug, but isn't and the program seems to work OK still.
To make my program more manageable, I have split it into separate .py files.
One file (called globs.py) is a list of global variables in the form
global var_1
global var_2
...
Then I import globs into my other files.
In another file I can set the variable, thus...
import globs
globs.var_1 = "some value"
In a third file I can use it..
import globs
if globs.var_1 == "something":
...
So far, all is as expected, but...
I just found out if the variable is NOT mentioned in the globs.py file at all, the program still seems to work OK.
Is this intended behavior? Any other programming language would give a 'variable not found' error.
If it is intended, why should I even setup any variables in globs.py?
What are the drawbacks?
Thanks, Mark.

Related

Multiple Transforms for VSCode Snippet

I've got a few snippets set up and working as I would like to, but I'm having a hard time getting one snippet to work where I believe I will need to have multiple transforms occur?
Essentially I have a TypeScript Interface defined for one of my components.
i.e. IRadioButtonListProps.ts which is inside of an Interfaces folder. The Interfaces folder has a sibling folder named Theme containing an interface named IRadioButtonListTheme.ts
Inside of IRadioButtonListProps I'm trying to stub out the entire interface. The snippet I currently have stubs out the interface like...
import * as React from 'react';
import IRadioButtonListPropsTheme from '../Theme/IRadioButtonListPropsTheme';
export interface IRadioButtonListPropsProps {
...props...
}
export default IRadioButtonListPropsProps;
The import line inside of the snippet is...
"import I${TM_FILENAME_BASE/(.*)\\..+$/$1/}Props from './Interfaces/I${TM_FILENAME_BASE/(.*)\\..+$/$1/}Props';"
What I'm trying to have happen and can't seem to figure out is how to also remove the word "Props". So instead of import IRadioButtonListPropsTheme... I would get import import IRadioButtonListTheme....
At the same time, I want to remove all extensions, including those of the form *.abc.abc ("two" extensions) and *.abc (one simple extension).
Is this possible?
It isn't crystal clear what you what but try:
"import ${TM_FILENAME/((\\w*)Props)*?(\\..*)/$2/}Theme from './Interfaces/${TM_FILENAME/((\\w*)Props)*?(\\..*)/$2/}Theme';"
which results in:
import IRadioButtonListTheme from './Interfaces/IRadioButtonListTheme';
from IRadioButtonListProps.ts
and
import CheckboxListTheme from './Interfaces/CheckboxListTheme';
from CheckboxListProps.test.tsx
[Edit] Here is a simpler version which I think also works:
"import ${TM_FILENAME/(Props)*?(\\..*)//}Theme from './Interfaces/${TM_FILENAME/(Props)*?(\\..*)//}Theme';"
match any "Props", if any, replace with nothing.
match from first \. to end of filename, replace with nothing.

Can't save figure as .eps [gswin32c is not recognized]

I'm using Enthought Canopy with PyLab(64-bit). For my report I need to use Latex (XeLaTex) and the plots are done with matplotlib.
To have an first idea I just copied the second example from http://matplotlib.org/users/usetex.html and compiled it. It looks fine and I can save it as a normal png without problems. However if i try to save it as .eps or.ps it does not work and an error appears:
invalid literal for int() with base 10: "
Additionaly in the Pylab shell it shows:
'gswin32c' is not recognized as an internal or external command, operable program or batch file'.
If I save it as .pdf I have no problems except the text is all black instead of being red and blue. This is a problem because in my plots I have two axes and I need them colorized for better readability.
If I then try to delete some lines from the example given (all text) I still cannot save it as .eps nor .ps. I can't figure out the problem and all the other topics related to this have not given me an insight. So I really need your help because I can't use .png for my report.
Thank you in advance!!!
I finally managed to solve this problem. It might look weird but maybe other people can benefit from it.
The solution might depend upon the software you use. I use Enthought Canopy (Python) and MikTeX 2.9 under W8 64bit.
If you want to output .ps and .eps files with matplotlib using the 'text.usetex': True option then you will encounter the problem posted above.
Solution:
Download and install Ghostscript (32bit) from http://www.ghostscript.com/download/gsdnld.html.
Download ps2eps-1.68.zip from http://www.tm.uka.de/~bless/ps2eps. The proceeding is given in the manual, however I like to point out the part with the environment variables. In this last step you need to go to Control Panel --> System --> Advanced system settings. Then click on the header 'Advanced' and on the bottom of the window you see 'Environment Variables' on which you click. Then you use the 'New'-Button for User Variables for USERNAME. Then you type in as variable name 'ps2eps' and for variable value you type in the actual path where you have saved the ps2eps.pl file. In my case this is 'C:\Program Files (x86)\ps2eps\bin\'. You can check if you type 'ps2eps' in the command-window.
Download xpdfbin-win-3.03.zip from http://www.foolabs.com/xpdf/download.html. You only need the file 'pdftops.exe'. However I could not assign a path like in step 2. I solved this by putting the 'pdftops.exe' in the MikTeX 2.9 folder. The exact location for me was 'C:\Program Files\MiKTeX 2.9\miktex\bin\x64'.
I was then able to save figures as .ps and have no more any error messages. Remember to use the settings proposed on http://matplotlib.org/users/usetex.html under 'postscript options'.
In myself used the following settings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.rc('font', **{'family':'serif', 'serif':['Computer Modern Roman'],
'monospace':['Computer Modern Typewriter']})
params = {'backend': 'ps',
'text.latex.preamble': [r"\usepackage{upgreek}",
r"\usepackage{siunitx}",
r"\usepackage{amsmath}",
r"\usepackage{amstext}",],
'axes.labelsize': 18,
#'axes.linewidth': 1,
#'text.fontsize':17,
'legend.fontsize': 10,
'xtick.labelsize': 13,
#'xtick.major.width' : 0.75,
'ytick.labelsize': 13,
'figure.figsize': [8.8,6.8],
#'figure.dpi': 120,
'text.usetex': True,
'axes.unicode_minus': True,
'ps.usedistiller' : 'xpdf'}
mpl.rcParams.update(params)
mpl.rcParams.update({'figure.autolayout':True})
(whereas many of the params are just for my own purpose later in the plots)
As a beginner I am not well informed about the dependence from the 'backend' used if you are running a script from your python console. I however used this without any --pylab settings in before and I do not know if one needs to switch the backend manually if he is working already in a console with a specific matplotlib backend.
I had the same problem and my problem was a font adjustment in the python code that is :
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
when I remove this iit works fine and now i can save eps.
So be sure that any shortest working example is working for you or not then check the font and other style edits in your code. This may help.

Python Relative Path Import from subfolder

first post to SO, so if I'm missing some details, please forgive me.
Is there a way to use relative paths from another subfolder without resorting to modifying sys.path via os? Eventually this will be run from a cgi webserver so I'd rather stay away from any -m arguments to python.exe.
I'm using Python 2.7.3 and have a file/directory structure of the following :
| myprog.py
|
+---functions
| myfunctions.py
| __init__.py
|
\---subfolder
mysub.py
In the root, I have a single .py file, called myprog.py :
#file .\myprog.py
from functions import *
hello("Hi from Main")
In the functions folder I have two files, init.py, myfunctions.py :
#The File: functions\__init__.py :
from myfunctions import *
#The File: functions\myfunctions.py :
def hello(sometext):
print sometext
And finally, in the subfolder, I have :
#The File: subfolder\mysub.py :
from ..functions import *
hello("Hi From mysubprogram")
The myprog.py executes fine (when running python.exe myprog.py from the parent folder), printing "Hi From Main", however, the mysub.py (when executed from the subfolder) keeps putting the error: ValueError: Attempted relative import in non-package
I have tried varying combinations in mysub.py such as from ..functions.myfunctions import * yet none yields the desired result.
I have read a few relevant articles :
using __init__.py
How to import classes defined in __init__.py
http://docs.python.org/2/tutorial/modules.html#packages-in-multiple-directories
But just can't figure this out. Oh, and once I get this working, I would like to remove the import *'s wherever possible, however, I'd rather not have to put the full paths to the hello function each time it's called, so any advise there or on cleaning up the init.py (using all or in another manner) would be a bonus.
Thanks Blckknght EDIT, I also found the below :
Relative imports for the billionth time
Which, if what I'm requesting isn't possible, perhaps I'm asking the wrong thing. If this is just outright bad practice, is the right way to accomplish my goal using sys.path or is there something else someone can recommend (like not calling functions from ../folders) ?
I think the issue has to do with how you are running the mysub.py script. Python doesn't tend to do well with scripts in packages, since the main script module is always named __main__ rather than its usual name.
I think you can fix this by running mysub with python -m subfolder.mysub, or by manipulating the __package__ variable in mysub.py (as described by PEP 366). It's not neat, unfortunately.

Python program to extend short urls that integrates with Stata

I have a dataset containing thousands of tweets. Some of those contain urls but most of them are in the classical shortened forms used in Twitter. I need something that gets the full urls so that I can check the presence of some particular websites. I have solved the problem in Python like this:
import urllib2
url_filename='C:\Users\Monica\Documents\Pythonfiles\urlstrial.txt'
url_filename2='C:\Users\Monica\Documents\Pythonfiles\output_file.txt'
url_file= open(url_filename, 'r')
out = open(url_filename2, 'w')
for line in url_file:
tco_url = line.strip('\n')
req = urllib2.urlopen(tco_url)
print >>out, req.url
url_file.close()
out.close()
Which works but requires that I export my urls from Stata to a .txt file and then reimport the full urls. Is there some version of my Python script that would allow me to integrate the task in Stata using the shell command? I have quite a lot of different .dta files and I would ideally like to avoid appending them all just to execute this task.
Thanks in advance for any answer!
Sure, this is possible without leaving Stata. I am using a Mac running OS X. The details might differ on your operating system, which I am guessing is Windows.
Python and Stata Method
Say we have the following trivial Python program, called hello.py:
#!/usr/bin/env python
import csv
data = [['name', 'message'], ['Monica', 'Hello World!']]
with open('data.csv', 'w') as wsock:
wtr = csv.writer(wsock)
for i in data:
wtr.writerow(i)
wsock.close()
This "program" just writes some fake data to a file called data.csv in the script's working directory. Now make sure the script is executable: chmod 755 hello.py.
From within Stata, you can do the following:
! ./hello.py
* The above line called the Python program, which created a data.csv file.
insheet using data.csv, comma clear names case
list
+-----------------------+
| name message |
|-----------------------|
1. | Monica Hello World! |
+-----------------------+
This is a simple example. The full process for your case will be:
Write file to disk with the URLs, using outsheet or some other command
Use ! to call the Python script
Read the output into Stata using insheet or infile or some other command
Cleanup by deleting files with capture erase my_file_on_disk.csv
Let me know if that is not clear. It works fine on *nix; as I said, Windows might be a little different. If I had a Windows box I would test it.
Pure Stata Solution (kind of a hack)
Also, I think what you want to accomplish can be done completely in Stata, but it's a hack. Here are two programs. The first simply opens a log file and makes a request for the url (which is the first argument). The second reads that log file and uses regular expressions to find the url that Stata was redirected to.
capture program drop geturl
program define geturl
* pass short url as first argument (e.g. http://bit.ly/162VWRZ)
capture erase temp_log.txt
log using temp_log.txt
copy `1' temp_web_file
end
The above program will not finish because the copy command will fail (intentionally). It also doesn't clean up after itself (intentionally). So I created the next program to read what happened (and get the URL redirect).
capture program drop longurl
program define longurl, rclass
* find the url in the log file created by geturl
capture log close
loc long_url = ""
file open urlfile using temp_log.txt , read
file read urlfile line
while r(eof) == 0 {
if regexm("`line'", "server says file permanently redirected to (.+)") == 1 {
loc long_url = regexs(1)
}
file read urlfile line
}
file close urlfile
return local url "`long_url'"
end
You can use it like this:
geturl http://bit.ly/162VWRZ
longurl
di "The long url is: `r(url)'"
* The long url is: http://www.ciwati.it/2013/06/10/wdays/?utm_source=twitterfeed&
* > utm_medium=twitter
You should run them one after the other. Things might get ugly using this solution, but it does find the URL you are looking for. May I suggest that another approach is to contact the shortening service and ask nicely for some data?
If someone at Stata is reading this, it would be nice to have copy return HTTP response header information. Doing this entirely in Stata is a little out there. Personally I would use entirely Python for this sort of thing and use Stata for the analysis of data once I had everything I needed.

Testing a python recipe

I want to run a python recipe I found, but I don't know how as it imports from another one!
For example, I would like to test the code here.
I have downloaded it and also downloaded this one as it uses it.
So how can I test the this code by passing the needed parameter as below?!
>>> G = {'s':{'u':10, 'x':5}, 'u':{'v':1, 'x':2}, 'v':{'y':4}, 'x':{'u':3, 'v':9, 'y':2}, 'y':{'s':7, 'v':6}}
>>> Dijkstra.Dijkstra(G,'s','v')
I have added the two files in one of the python paths, and imported both but still get error
Could you please give me some advice on simple way to test this code?
You really should put the files in your current directory if you are just testing, instead of putting them in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ as that path is reserved for the Python standard library.
It seems that the second recipe, the Priority Dictionary, needs to be put in a file called priodict.py since the Dijkstra code imports from priodict. So, you should have the following files in your current directory: Dijkstra.py, priodict.py. Then you can just start Python and do import Dijkstra, and it should work.
Also, don't modify the Dijkstra code to remove the import as you apparently did...