Using win32com.client, I'm attempting to create a simple shortcut in a folder. The shortcut however I would like to have arguments, except I keep getting the following error.
Traceback (most recent call last):
File "D:/Projects/Ms/ms.py", line 153, in <module>
scut.TargetPath = '"C:/python27/python.exe" "D:/Projects/Ms/msd.py" -b ' + str(loop7)
File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 570, in __setattr__
raise AttributeError("Property '%s.%s' can not be set." % (self._username_, attr))
AttributeError: Property '<unknown>.TargetPath' can not be set.
My code looks like this. I've tried multiple different variates but can't seem to get it right. What am I doing wrong?
ws = win32com.client.Dispatch("wscript.shell")
scut = ws.CreateShortcut("D:/Projects/Ms/TestDir/testlink.lnk")
scut.TargetPath = '"C:/python27/python.exe" "D:/Projects/Ms/msd.py" -b 0'
scut.Save()
Your code works for me without error. (Windows XP 32bit, Python 2.7.5, pywin32-216).
(I slightly modified your code because TargetPath should contain only executable path.)
import win32com.client
ws = win32com.client.Dispatch("wscript.shell")
scut = ws.CreateShortcut('run_idle.lnk')
scut.TargetPath = '"c:/python27/python.exe"'
scut.Arguments = '-m idlelib.idle'
scut.Save()
I got AttributeError similar to yours when I tried following (assign list to Arguments property.)
>>> scut.Arguments = []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python27\lib\site-packages\win32com\client\dynamic.py", line 570, in __setattr__
raise AttributeError("Property '%s.%s' can not be set." % (self._username_, attr))
AttributeError: Property '<unknown>.Arguments' can not be set.
"..TargetPath should contain only [an] executable path." is incorrect in two ways :
The target may also contain the executable's arguments.
For instance, I have a file [ D:\DATA\CCMD\Expl.CMD ] whose essential line of code is
START Explorer.exe "%Target%"
An example of its use is
D:\DATA\CCMD\Expl.CMD "D:\DATA\SYSTEM - NEW INSTALL PROGS"
This entire line is the "executable" you are referring to.
The target doesn't have to be an "executable" at all. It may be any file in which the OS can act upon, such as those file types whose default actions run executable with the files as its arguments, such as :
"My File.txt"
The "default action" on this file type is to open it with a text editor. The actual executable file run isn't explicit.
Related
I'm doing something basic with python, and I'm getting a pretty common error, but not able to find exactly what's wrong. I'm trying to use a custom module (built by someone else). I have the folder structure like this:
There is the test folder, and I have a file testing.py within that:
The contents of testing.py is:
from util import get_data, plot_data
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
When I run this file, using python testing.py, I get this:
I went through the other questions that speak about paths, and this looks fine, so not sure what I am missing here. My environment is setup using conda, and the environment is active.
EDIT
As per #allan-wind, I made the relative edit, which got me past the error, but now getting different errors:
I tried the relative import, and it got past that error, but then it is now throwing this error:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 190, in get_context
ctx = _concrete_contexts[method]
KeyError: 'fork'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "grade_analysis.py", line 21, in <module>
from grading.grading import (
File "E:\_Repo\GT\CS7646\mls4tsp23\grading\grading.py", line 15, in <module>
multiprocessing.set_start_method('fork')
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 246, in set_start_method
self._actual_context = self.get_context(method)
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 238, in get_context
return super().get_context(method)
File "C:\ProgramData\Anaconda3\envs\ml4t\lib\multiprocessing\context.py", line 192, in get_context
raise ValueError('cannot find context for %r' % method)
ValueError: cannot find context for 'fork'
`
There are a number of ways to specify how to find modules:
Use a relative import:
from .util import get_data, plot_data
Set the environment variable PYTHONPATH includes the directory where you module resides.
See sys.meta_path
Just place utils in the same folder as your testing.py and the python interpreter you put that directory in your path. Other solutions would be to place utils in a directory that is already in your path, since if thats not the case, you cant import from "above" the current directory
When I executed in Python command
rssa = importr('Rssa')
I got eroor
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
rssa = importr('Rssa')
File "C:\Python34\lib\site-packages\rpy2\robjects\packages.py", line 412, in importr
version = version)
File "C:\Python34\lib\site-packages\rpy2\robjects\packages.py", line 178, in __init__
self.__fill_rpy2r__(on_conflict = on_conflict)
File "C:\Python34\lib\site-packages\rpy2\robjects\packages.py", line 280, in __fill_rpy2r__
super(SignatureTranslatedPackage, self).__fill_rpy2r__(on_conflict = on_conflict)
File "C:\Python34\lib\site-packages\rpy2\robjects\packages.py", line 233, in __fill_rpy2r__
rpyobj = conversion.ri2ro(riobj)
File "C:\Python34\lib\functools.py", line 707, in wrapper
return dispatch(args[0].__class__)(*args, **kw)
File "C:\Python34\lib\site-packages\rpy2\robjects\__init__.py", line 101, in _
return SignatureTranslatedFunction(obj)
File "C:\Python34\lib\site-packages\rpy2\robjects\functions.py", line 150, in __init__
raise ValueError("Error: '%s' already in the translation table. This means that the signature of the R function contains the parameters '%s' and/or '%s' <sigh> in multiple copies." %(r_param, r_param, prm_translate[py_param]))
ValueError: Error: '...' already in the translation table. This means that the signature of the R function contains the parameters '...' and/or '...' <sigh> in multiple copies.
Other packages are imported without problem, as example
stats = importr('stats')
tseries = importr('tseries')
forecast = importr('forecast')
I was looking for such problem, but I could not find nothing close. Please, suggest some decision of this problem.
This was caused by bug in Rssa when it tries to take control over 'decompose' function (which is exported from 'stats' package). In particular, in the list of formals '...' is added twice and this is what rpy2 is complaining about.
This will be fixed in the subsequent Rssa releases.
The only workaround is to comment out in R/common.R the following line:
formals(decompose.default) <- c(formals(decompose.default), alist(... = ))
And reinstall Rssa from source. This might be non-trivial on Windows, though R windows builder can help here.
I'm trying to dispay process if and pool names of iis in python.
Here is my python code:
import wmi
c = wmi.WMI('.', namespace="root/WebAdministration")
c.query("select ProcessId from WorkerProcess")
it fails:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\wmi.py", line 1009, in query
return [ _wmi_object (obj, instance_of, fields) for obj in self._raw_query(wql) ]
File "C:\Python27\lib\site-packages\win32com\client\util.py", line 84, in next
return _get_good_object_(self._iter_.next(), resultCLSID = self.resultCLSID)
pywintypes.com_error: (-2147217389, 'OLE error 0x80041013', None, None)
I also tried:
for p in c.WorkerProcess:
print p.ProcessId
which does not work either.
Now here is a very similar visualbasic script code that works fine:
Set oWebAdmin = GetObject("winmgmts:root\WebAdministration")
Set processes = oWebAdmin.InstancesOf("WorkerProcess")
For Each w In processes
WScript.Echo w.ProcessId
WScript.Echo w.AppPoolName
Next
the documentation is:
http://msdn.microsoft.com/en-us/library/microsoft.web.administration.workerprocess(v=vs.90).aspx
It looks like I'm supposed to instantiate but I cannot figure out how.
Any ideas how to get it to work in python?
Actually my code was correct. I just needed to run it with admin preivileges.
I am attempting to generate bindings for a WSDL with PyXB, and it is giving the AssertionError exception in the title.
My understanding, based on the PyXB documentation, is that the bundle archive for http://www.w3.org/1999/xhtml is included with PyXB. However, something appears to be wrong. It either does not get used, or it has incorrect contents.
I use the following command line to attempt to generate the bindings:
python c:\Python27\Scripts\pyxbgen.py --wsdl-location=http://xx.xxx.xxx.xxx/YYY.asmx?WSDL --module=client --write-for-customization
The traceback:
Traceback (most recent call last):
File "c:\Python27\Scripts\pyxbgen.py", line 51, in <module> generator.resolveExternalSchema()
File "c:\Python27\lib\site-packages\pyxb\binding\generate.py", line 2647, in resolveExternalSchema
schema = converter(self, sl)
File "c:\Python27\Scripts\pyxbgen.py", line 28, in WSDLToSchema
spec = wsdl.definitions.createFromDOM(pyxb.utils.domutils.StringToDOM(xmld,
location_base=wsdl_uri), process_schema=True, generation_uid=generator.generationUID())
File "c:\Python27\lib\site-packages\pyxb\binding\basis.py", line 1767, in createFromDOM
return self._createFromDOM(node, expanded_name, **kw)
File "c:\Python27\lib\site-packages\pyxb\binding\basis.py", line 1791, in _createFromDOM
return element.CreateDOMBinding(node, self.elementForName(expanded_name), **kw)
File "c:\Python27\lib\site-packages\pyxb\binding\basis.py", line 1735, in elementForName
assert 'elementBinding' in elt_en.namespace()._categoryMap(), 'No element bindings in %s' % (elt_en.namespace(),)
AssertionError: No element bindings in http://www.w3.org/1999/xhtml
In addition, I set the PYXB_ARCHIVE_PATH environment variable to:
C:\Python27\Lib\site-packages\pyxb\bundles\common\raw
I am not sure if this is the correct way to do this. I also tried specifying the --archive-path command line option as well, but I got the same error back.
Probably you need to use:
--archive-path=${PYXB_ROOT}/pyxb/bundles/common//:+
as the argument. This recursively searches for available namespaces in the common bundles first, then includes any other search paths. There's an example in the manual that's close to this.
I have a program that uses the win32com library to control iTunes, but have been having some issues getting it to compile into an executable. The problem seems to revolve around using DispatchWithEvents instead of Dispatch. I've created a very simple program to illustrate my problem:
import win32com.client
win32com.client.gencache.is_readonly = False #From py2exe wiki
class ITunesEvents(object):
def __init__(self): self.comEnabled = True
def OnCOMCallsDisabledEvent(self, reason): self.comEnabled = False
def OnCOMCallsEnabledEvent(self): self.comEnabled = True
# The first line works in the exe, the second doesn't.
itunes = win32com.client.Dispatch("iTunes.Application")
#itunes = win32com.client.DispatchWithEvents("iTunes.Application", ITunesEvents)
lib = getattr(itunes, "LibraryPlaylist")
src = getattr(lib, "Source")
playlists = getattr(src, "Playlists")
print "Found %i playlists." % getattr(playlists, "Count")
Using Dispatch, the program compiles and runs correctly. Using DispatchWithEvents, the program runs fine when called from the command line, but produces the following error when running the exe:
Traceback (most recent call last):
File "sandbox.py", line 16, in <module>
itunes = win32com.client.DispatchWithEvents("iTunes.Application", ITunesEvents)
File "win32com\client\__init__.pyc", line 252, in DispatchWithEvents
File "win32com\client\gencache.pyc", line 520, in EnsureModule
File "win32com\client\gencache.pyc", line 287, in MakeModuleForTypelib
File "win32com\client\makepy.pyc", line 259, in GenerateFromTypeLibSpec
File "win32com\client\gencache.pyc", line 141, in GetGeneratePath
IOError: [Errno 2] No such file or directory: '[distDir]\\library.zip\\win32com\\gen_py\\__init__.py'
I've also tried using PyInstaller, which gives a similar error:
File "<string>", line 16, in <module>
File "[outDir]/win32com.client", line 252, in DispatchWithEvents
File "[outDir]/win32com.client.gencache", line 520, in EnsureModule
File "[outDir]/win32com.client.gencache", line 287, in MakeModuleForTypelib
File "[outDir]/win32com.client.makepy", line 286, in GenerateFromTypeLibSpec
File "[outDir]/win32com.client.gencache", line 550, in AddModuleToCache
File "[outDir]/win32com.client.gencache", line 629, in _GetModule
File "[pyinstallerDir]\iu.py", line 455, in importHook
raise ImportError, "No module named %s" % fqname
ImportError: No module named win32com.gen_py.9E93C96F-CF0D-43F6-8BA8-B807A3370712x0x1x13
I know I can manually add the typelib in my setup.py file, but I'd like to run the code on computers with different versions of iTunes without recompiling so I'd prefer to dynamically create it. If there's no way to do this with the setup/spec, maybe there is another way to load the events? Thanks.
Addition:
Thanks to Ryan, I found I could take the generated py file and after a little digging, was able to come up with the following.
Take the generated py file (from makepy.py) and rename it somewhere like cominterface.py. Then you'll need to do the following to actually create the COM object with event handler.
import cominterface
from types import ClassType
from win32com.client import EventsProxy, _event_setattr_
class ItunesEvents:
'''iTunes events class. See cominterface for details.'''
def OnPlayerPlayEvent(self, t):print "Playing..."
def OnPlayerStopEvent(self, t): print "Stopping..."
itunes = cominterface.iTunesApp()
rClass = ClassType("COMEventClass", (itunes.__class__, itunes.default_source, ItunesEvents), {'__setattr__': _event_setattr_})
instance = rClass(itunes._oleobj_)
itunes.default_source.__init__(instance, instance)
#ItunesEvents.__init__(instance) #Uncomment this line if your events class has __init__.
itunes = EventsProxy(instance)
Then you can go about your business.
I was experiencing the exact same error.
This link put me in the right direction -->
http://www.py2exe.org/index.cgi/UsingEnsureDispatch
however it mentions that :
NB You must ensure that the python...\win32com.client.gen_py dir does not exist
to allow creation of the cache in %temp%
Which was a bit confusing.
What solved it for me was renaming "C:\Python26\Lib\site-packages\win32com\gen_py" to "C:\Python26\Lib\site-packages\win32com\gen_pybak" (when running py2exe)
This is the official way to do it.
(Edit: copied verbatim example from that link above)
import win32com.client
if win32com.client.gencache.is_readonly == True:
#allow gencache to create the cached wrapper objects
win32com.client.gencache.is_readonly = False
# under p2exe the call in gencache to __init__() does not happen
# so we use Rebuild() to force the creation of the gen_py folder
win32com.client.gencache.Rebuild()
# NB You must ensure that the python...\win32com.client.gen_py dir does not exist
# to allow creation of the cache in %temp%
# Use SAPI speech through IDispatch
from win32com.client.gencache import EnsureDispatch
from win32com.client import constants
voice = EnsureDispatch("Sapi.SpVoice", bForDemand=0)
voice.Speak( "Hello World.", constants.SVSFlagsAsync )
Instead of depending on the cache, I'd recommend going into the local cache directory, copying the generated file into your local project file, and naming it something like ITunesInterface.py, and calling to that explicitly. This will make py2exe pull it into your compiled app.