<unknown>.TargetPath can not be set - python-2.7

I'm attempting to write a script that can be deployed and remotely run on a number of target computers with the end result of having an existing shortcut replaced by one that runs the exact same program, but at high priority. Here is my script:
import os, winshell
from win32com.client import Dispatch
from comtypes.client import CreateObject
# from comtypes.gen import IWshRuntimeLibrary
desktop = winshell.desktop()
path = os.path.join(desktop, 'Test Short.lnk')
target = r'\%HOMEDRIVE%\\Apps\\Ellie Mae\\Encompass\\AppLauncher.exe'
wDir = r'\%HOMEDRIVE%\\Apps\\Ellie Mae\\Encompass'
icon = r'\%SystemRoot%\\Installer\\{3E9C4FBE-4E6C-4389-A4B3-4AE027D0BF2E}\\Icon3E9C4FBE2.ico'
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.TargetPath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()
I'm running into an Attribute error, as follows:
AttributeError: Property '<unknown>.TargetPath' can not be set.
For reference, here is where I got most of my code.
I attempted to search out an answer, and I came across this thread. However, following the accepted suggestion yields:
ImportError: cannot import name IWshRuntimeLibrary
My confusion comes from why I'm not able to set the TargetPath property to begin with. As happens so often, it seems as if the OP from the linked thread and I are the only two people reporting this problem. Does anyone know why that might be happening and what I can do to fix it?

Related

how to Looping python scripts together

I have two files. An 'initialization' script aka file1.py and a 'main code' script aka 'main_code.py'. The main_code.py is really a several hundred line .ipynb that was converted to a .py file. I want to run the same skeleton of the code with the only adjustment being to pass in the different parameters found in the 'file1.py' script.
In reality, it is much more complex than what I have laid out below with more references to other locations / DBs and what not.
However, I receive errors such as 'each_item[0]' is not defined. I can't seem to be able to pass in the values/variables that come from my loop in file1.py to my script that is contained inside the loop.
Must be doing something very obviously wrong as I imagine this is a simple fix
file1.py:
import pandas as pd
import os
import bumpy as np
import jaydebeapi as jd
#etc...
cities = ['NYC','LA','DC','MIA'] # really comes from a query/column
value_list = [5,500,5000,300] # comes from a query/column
zipped = list(zip(cities,value_list)) # make tuples
for each_item in zipped:
os.system('python loop_file.py')
# where I'm getting errors.
main_code.py:
names = each_item[0]
value = each_item[1]
# lots of things going on here in real code but for simplicity...
print value = value * 4
print value

Do not reload all Flask apps

I'm using flask blueprints just as written here:
http://flask.pocoo.org/docs/0.12/patterns/appdispatch/
Specifically, I'm running the following piece of code:
from werkzeug.wsgi import DispatcherMiddleware
from frontend_app import application as frontend
from backend_app import application as backend
application = DispatcherMiddleware(frontend, {
'/backend': backend
})
Flask has an awesome feature of reloading application as it detects change in code. However, in my case it is not desirable for both apps: backend app is too heavy to be reloaded every few minutes. When I reload fronend, backend gets reloaded as well and it takes too long. Is there any way to reload only app that was changed?
I realize it might be difficult, because as far as I understand at this point
application = DispatcherMiddleware(frontend, {
'/backend': backend
})
applications are merged into a single one and they are not separate anymore.
Anyway, maybe there is a different way to achieve what I want?
Thanks.
I am not sure if there is anything direct for doing such thing. Only thing I can think if you preventing a reinitialization of your module.
See a below example of how one can achieve this
reloadme.py
import sys
if 'reloadme' in sys.modules and hasattr(sys.modules['reloadme'], '__MODULE_LOADED'):
print ("module is being reloaded")
mod = sys.modules['reloadme']
x = mod.x
else:
print ("Loading module for first time")
__MODULE_LOADED = True
x = 2
def printx():
print (x)
reloadtest.py
from importlib import reload
import reloadme
reloadme.printx()
reloadme.x = 10
reloadme.printx()
print("Reloading reloadme to check if x is changed back to 2")
reload(reloadme)
reloadme.printx()
The output of running reloadtest.py will be as below
Loading module for first time
2
10
Reloading reloadme to check if x is changed back to 2
Reloading module
10

how to create and polulate a geometry columns in sqlite3

I am creating a test database on my local machine so I can test some calculations before moving to a bigger run to be saved against the actual postgres database. But I can't get sqlite3 to create and save data to my geom columns (which is being correctly created by python). It seems like the geom column doesn't get created either. Any help will be appreciated.
conn = lite.connect('geom_test.db')
c = conn.cursor()
c.execute("""CREATE TABLE test
(
lat double precision,
long double precision,
speed double precision)"""))
c.execute("""
SELECT AddGeometryColumn('test', 'geom',
4326, 'POINT', 'XY');""")
line = ogr.Geometry(ogr.wkbLineString)
line.AddPoint_2D(lon,lat)
line = line.ExportToWkt()
qry ="INSERT INTO sequence VALUES (?,?,?,?);"
conn = lite.connect('geom_test.db')
c = conn.cursor()
c.executemany(qry, data) #data is 4 columns dict
c.close()
conn.commit()
conn.close()
It looks like you're using SpatiaLite, which adds functionality to SQLite. See Recipe #6: Creating a new Geometry column. The next slide shows how to load some simple geometries into the table.
See the main web resource for SpatiaLite, with cookbooks, references, etc. And if you need to view the geometries, try QGIS.
You need to import the spatialite shared library :
import sqlite3 as lite
from os.path import realpath
conn = lite.connect('geom_test.db')
library_path = "/usr/local/lib/mod_spatialite.so" # on my ubuntu linux
conn.enable_load_extension(True)
conn.load_extension(realpath(library_path))
Or another way to load the extension :
conn.execute("SELECT load_extension(?, 'sqlite3_modspatialite_init');",
(realpath(library_path),))
On windows the name will be 'mod_spatialite.dll' (Also be careful to the path provided to the load_extension(), ie. properly escaping problematic characters and resolving symbolic links before calling it).
Anyway this page on SpatiaLite website show some details about the loading of the shared library.
Edit:
The loading will raise an OperationalError if it fails. If it success, you can check if it use the versions you expected (and do the operations you were trying to do, of course):
vs = str([i for i in c.execute("""SELECT spatialite_version()""")])
vgeos = str([i for i in c.execute("""SELECT geos_version()""")]
print('Spatialite {} (GEOS {})'.format(
vs.strip("()[]',"), vgeos.strip("()',[]")))
It looks like you're using PostGIS, which adds functionality to PostgreSQL. Included in this is the AddGeometryColumn function. This won't be available to SQLite, as it isn't a standard function.

path apps in django

I wanna get absolute path all installed_apps in "setting.py" .
app_list = [ app for app in Myproject.settings.INSTALLED_APPS ]
I list of application but how i can get absolute path all of them.
Thank you.
It's not really possible to do what you want. I mean you can get almost there, but there's no real functionality for this, and in particular, Python doesn't distinguish between classes, methods, and variables. They all count as attributes of the module.
First, INSTALLED_APPS is a tuple of strings. So, in order to get any useful information, you're going to have load them as modules:
for app in settings.INSTALLED_APPS:
module = __import__(app)
Then, once you have the actual module, you can call dir on it to get a list of its attributes:
for app in settings.INSTALLED_APPS:
module = __import__(app)
print dir(module)
And, that's about as far as you can go. It's going to output everything set in the module, not just classes. From here, about the only recourse I can think of to weed out everything but classes is to assume that naming conventions were followed and look for items that start with a capital letter. That's not exactly scientific, but that's all you got.
Today I solved my problem. I write this code and its just working. For limited name class I find name of class that inherent from "models.Model" . you can change it and enjoy that.also this code find files in depth 1 of modules. it can change.
app_list = [app for app in training.settings.INSTALLED_APPS if "task" in app]
for module in app_list:
module1 = __import__(module)
temp = module1.__path__
files_path = [temp[0] + os.sep + files_name for files_name in os.listdir(temp[0]) if
os.path.splitext(files_name)[1] == ".py"]
p = re.compile(r'class\s*\w*\s*\(models.Model\):')
for file in files_path:
infile = open(file)
text = infile.read()
all_class = p.findall(text)
print [class_name[6:][:-15] for class_name in all_class]

Dynamically generating Hudson custom workspace path

I'm trying to get a Hudson job to get built in a custom workspace path that is automatically generated using yyyyMMdd-HHmm. I can get the $BUILD_ID variable expanded as mentioned in bug 3997, and that seems to work fine. However, the workspace path is incorrect as it is of the format yyyy-MM-dd_HH-mm-ss. I've tried using the ZenTimestamp plugin v2.0.1, which changes the $BUILD_ID, but this only seems to take effect after the workspace is created.
Is there a method of defining a custom workspace in the manner that I want it?
You can use a groovy script to achieve that.
import hudson.model.*;
import hudson.util.*;
import java.util.*;
import java.text.*;
import java.io.*;
//Part 1 : Recover build parameter
AbstractBuild currentBuild = (AbstractBuild) Thread.currentThread().executable;
def envVars= currentBuild.properties.get("envVars");
def branchName = envVars["BRANCH_NAME"];
//Part 2 : Define new workspace Path
def newWorkspace = "C:\\Build\\"+branchName;
//Part 3 : Change current build workspace
def newWorspaceFilePath = new FilePath(new File(newWorkspace));
currentBuild.setWorkspace(newWorspaceFilePath);