I have this script file in python running on S60:
import location
def current_location():
gsm_loc = location.gsm_location()
print gsm_loc
current_location()
instead of printing a tuple of mcc, mnc, lac and cellId it prints None.
on top of my python shell I see location between the capabilities included.
what can be the problem?
Development of the situation:
I thought maybe nevertheless, my problem is lack of capabilities. So I went to sign the PythonScriptShell file.
I used OPDA website - I know they sign all the capabilities but three - which I don't use.
I installed the signed PythonScriptShell file on my phone (N95). On the top the list of capabilities didn't change. tried to run the script again:
same result - prints None.
If anyone can help me with this, it's really important.
thank you.
I think I can answer now one part of the problem:
the reason for printing None is because there needed another capability: ReadDeviceData which wasn't included in the capabilities list on top of python shell.
still, remaining the other part of the problem, why this capability wasn't included when I signed PythonScriptShell file? It is not one of the three restricted capabilities.
I have same issue with all necessary scriptshell capabilities: 'PowerMgmnt', 'ReadDeviceData', 'WriteDeviceData', 'TrustedUI', 'ProtServ', 'SwEvent', 'Network services', 'LocalServices', 'ReadUserData', 'WriteUserData', 'Location', 'SurroundingsDD', 'UserEnviroment'.
Let's take a look at source code from PythonForS60/module-repo/dev-modules/location.py:
import e32
import _location
def gsm_location():
if e32.s60_version_info>=(3,0):
ret = _location.gsm_location()
if ret[4]==1: # relevant information ?
return (int(ret[0]),int(ret[1]),ret[2],ret[3])
else:
return None # information returned by _location.gsm_location() not relevant
else:
return _location.gsm_location()
On my Nokia E71 e32.s60_version_info == (3,1) and I get None value too.
I don't really know what means 'not relevant', but direct calling
>>> import _location
>>> _location.gsm_location()
(u'257', u'01', 555, 11, 0)
returns something close to my objective reality.
Related
I am trying to change the user of a print job in the queue, as I want to create it on a service account but send the job to another users follow-me printing queue. I'm using the win32 module in python. Here is an example of my code:
from win32 import win32print
JOB_INFO_LEVEL = 2
pclExample = open("sample.pcl")
printer_name = win32print.GetDefaultPrinter()
hPrinter = win32print.OpenPrinter(printer_name)
try:
jobID = win32print.StartDocPrinter(hPrinter, 1, ("PCL Data test", None, "RAW"))
# Here we try to change the user by extracting the job and then setting it again
jobInfoDict = win32print.GetJob(hPrinter, jobID , JOB_INFO_LEVEL )
jobInfoDict["pUserName"] = "exampleUser"
win32print.SetJob(hPrinter, jobID , JOB_INFO_LEVEL , jobInfoDict , win32print.JOB_CONTROL_RESUME )
try:
win32print.StartPagePrinter(hPrinter)
win32print.WritePrinter(hPrinter, pclExample)
win32print.EndPagePrinter(hPrinter)
finally:
win32print.EndDocPrinter(hPrinter)
finally:
win32print.ClosePrinter(hPrinter)
The problem is I get an error at the win32print.SetJob() line. If JOB_INFO_LEVEL is set to 1, then I get the following error:
(1804, 'SetJob', 'The specified datatype is invalid.')
This is a known bug to do with how the C++ works in the background (Issue here).
If JOB_INFO_LEVEL is set to 2, then I get the following error:
(1798, 'SetJob', 'The print processor is unknown.')
However, this is the processor that came from win32print.GetJob(). Without trying to change the user this prints fine, so I'm not sure what is wrong.
Any help would be hugely appreciated! :)
EDIT:
Using Python 3.8.5 and Pywin32 303
At the beginning I thought it was a misunderstanding (I was also a bit skeptical about the bug report), mainly because of the following paragraph (which apparently seems to be wrong) from [MS.Docs]: SetJob function (emphasis is mine):
The following members of a JOB_INFO_1, JOB_INFO_2, or JOB_INFO_4 structure are ignored on a call to SetJob: JobId, pPrinterName, pMachineName, pUserName, pDrivername, Size, Submitted, Time, and TotalPages.
But I did some tests and ran into the problem. The problem is as described in the bug: filling JOB_INFO_* string members (which are LPTSTRs) with char* data.
Submitted [GitHub]: mhammond/pywin32 - Fix: win32print.SetJob sending ANSI to UNICODE API (and none of the 2 errors pops up). It was merged to main on 220331.
When testing the fix, I was able to change various properties of an existing job, I was amazed that it didn't have to be valid data (like below), I'm a bit curious to see what would happen when the job would be executed (as now I don't have a connection to a printer):
Change pUserName to str(random.randint(0, 10000)) to make sure it changes on each script run (PrintScreens taken separately and assembled in Paint):
Ways to go further:
Wait for a new PyWin32 version (containing this fix) to be released. This is the recommended approach, but it will also take more time (and it's unclear when it will happen)
Get the sources, either:
from main
from b303 (last stable branch), and apply the (above) patch(1)
build the module (.pyd) and copy it in the PyWin32's site-packages directory on your Python installation(s). Faster, but it requires some deeper knowledge, and maintenance might become a nightmare
Footnotes
#1: Check [SO]: Run / Debug a Django application's UnitTests from the mouse right click context menu in PyCharm Community Edition? (#CristiFati's answer) (Patching UTRunner section) for how to apply patches (on Win).
I am accessing an Intersystems cache 2017.1.xx instance through a python process to get various attributes about the database in able to monitor the database.
One of the items I want to monitor is license usage. I wrote a objectscript script in a Terminal window to access license usage by user:
s Rset=##class(%ResultSet).%New("%SYSTEM.License.UserListAll")
s r=Rset.Execute()
s ncol=Rset.GetColumnCount()
While (Rset.Next()) {f i=1:1:ncol w !,Rset.GetData(i)}
But, I have been unable to determine how to convert this script into a Python equivalent. I am using the intersys.pythonbind3 import for connecting and accessing the cache instance. I have been able to create python functions that accessing most everything else in the instance but this one piece of data I can not figure out how to translate it to Python (3.7).
Following should work (based on the documentation):
query = intersys.pythonbind.query(database)
query.prepare_class("%SYSTEM.License","UserListAll")
query.execute();
# Fetch each row in the result set, and print the
# name and value of each column in a row:
while 1:
cols = query.fetch([None])
if len(cols) == 0: break
print str(cols[0])
Also, notice that InterSystems IRIS -- successor to the Caché now has Python as an embedded language. See more in the docs
Since the noted query "UserListAll" is not defined correctly in the library; not SqlProc. So to resolve this issue would require a ObjectScript with the query and the use of #Result set or similar in Python to get the results. So I am marking this as resolved.
Not sure which Python interface you're using for Cache/IRIS, but this Open Source 3rd party one is worth investigating for the kind of things you're trying to do:
https://github.com/chrisemunt/mg_python
I try to download a bingads report using python SDK, but I keep getting an error says: "Type not found: 'Aggregation'" after submitting a report request. I've tried all 4 options mentioned in the following link:
https://github.com/BingAds/BingAds-Python-SDK/blob/master/examples/v13/report_requests.py
Authentication process prior to request works just fine.
I execute the following:
report_request = get_report_request(authorization_data.account_id)
reporting_download_parameters = ReportingDownloadParameters(
report_request=report_request,
result_file_directory=FILE_DIRECTORY,
result_file_name=RESULT_FILE_NAME,
overwrite_result_file=True, # Set this value true if you want to overwrite the same file.
timeout_in_milliseconds=TIMEOUT_IN_MILLISECONDS
)
output_status_message("-----\nAwaiting download_report...")
download_report(reporting_download_parameters)
after a careful debugging, it seems that the program fails when trying to execute a command within "reporting_service_manager.py". Here is workflow:
download_report(self, download_parameters):
report_file_path = self.download_file(download_parameters)
then:
download_file(self, download_parameters):
operation = self.submit_download(download_parameters.report_request)
then:
submit_download(self, report_request):
self.normalize_request(report_request)
response = self.service_client.SubmitGenerateReport(report_request)
SubmitGenerateReport starts a sequence of events ending with a call to "_SeviceCall.init" function within "service_client.py", returning an exception "Type not found: 'Aggregation'"
try:
response = self.service_client.soap_client.service.__getattr__(self.name)(*args, **kwargs)
return response
except Exception as ex:
if need_to_refresh_token is False \
and self.service_client.refresh_oauth_tokens_automatically \
and self.service_client._is_expired_token_exception(ex):
need_to_refresh_token = True
else:
raise ex
Can anyone shed some light? .
Thanks
Please be sure to set Aggregation e.g., as shown here.
aggregation = 'Daily'
If the report type does not use aggregation, you can set Aggregation=None.
Does this help?
This may be a bit late 2 months after the fact but maybe this will help someone else. I had the same error (though I suppose it may not be the same issue). It does look like you did what I did (and I'm sure others will as well): copy-paste the Microsoft example code and tried to run it only to find that it didn't work.
I spent quite some time trying to debug the issue and it looked to me like the XML wasn't being searched correctly. I was using suds-py3 for the script at the time so I tried suds-community and everything just worked after that.
I also re-read the Bing Ads API walkthrough for getting started again and found that they recommend suds-jurko instead.
Long story short: If you want to use the bingads API don't use suds-py3, use either suds-community (which I can confirm works for everything I've used the API for) or suds-jurko (which is the one recommended by Microsoft).
I was trying to use xgoogle but I has not been updated for 3 years and I just keep getting no more than 5 results even if I set 100 results per page. If anyone uses xgoogle without any problem please let me know.
Now, since the only available(apparently) wrapper is xgoogle, the option is to use some sort of browser, like mechanize, but that is gonna make the code entirely dependant on google HTML and they might change it a lot.
Final option is to use the Custom search API that google offers, but is has a redicolous 100 requests per day limit and a pricing after that.
I need help on which direction should I go, what other options do you know of and what works for you.
Thanks !
It only needs a minor patch.
The function GoogleSearch._extract_result (Line 237 of search.py) calls GoogleSearch._extract_description (Line 258) which fails causing _extract_result to return None for most of the results therefore showing fewer results than expected.
Fix:
In search.py, change Line 259 from this:
desc_div = result.find('div', {'class': re.compile(r'\bs\b')})
to this:
desc_div = result.find('span', {'class': 'st'})
I tested using:
#!/usr/bin/python
#
# This program does a Google search for "quick and dirty" and returns
# 200 results.
#
from xgoogle.search import GoogleSearch, SearchError
class give_me(object):
def __init__(self, query, target):
self.gs = GoogleSearch(query)
self.gs.results_per_page = 50
self.current = 0
self.target = target
self.buf_list = []
def __iter__(self):
return self
def next(self):
if self.current >= self.target:
raise StopIteration
else:
if(not self.buf_list):
self.buf_list = self.gs.get_results()
self.current += 1
return self.buf_list.pop(0)
try:
sites = {}
for res in give_me("quick and dirty", 200):
t_dict = \
{
"title" : res.title.encode('utf8'),
"desc" : res.desc.encode('utf8'),
"url" : res.url.encode('utf8')
}
sites[t_dict["url"]] = t_dict
print t_dict
except SearchError, e:
print "Search failed: %s" % e
I think you misunderstand what xgoogle is. xgoogle is not a wrapper; it's a library that fakes being a human user with a browser, and scrapes the results. It's heavily dependent on the format of Google's search queries and results pages as of 2009, so it's no surprise that it doesn't work the same in 2013. See the announcement blog post for more details.
You can, of course, hack up the xgoogle source and try to make it work with Google's current format (as it turns out, they've only broken xgoogle by accident, and not very badly…), but it's just going to break again.
Meanwhile, you're trying to get around Google's Terms of Service:
Don’t misuse our Services. For example, don’t interfere with our Services or try to access them using a method other than the interface and the instructions that we provide.
They're been specifically asked about exactly what you're trying to do, and their answer is:
Google's Terms of Service do not allow the sending of automated queries of any sort to our system without express permission in advance from Google.
And you even say that's explicitly what you want to do:
Final option is to use the Custom search API that google offers, but is has a redicolous 100 requests per day limit and a pricing after that.
So, you're looking for a way to access Google search using a method other than the interface they provide, in a deliberate attempt to get around their free usage quota without paying. They are completely within their rights to do anything they want to break your code—and if they get enough hits from people doing things kind of thing, they will do so.
(Note that when a program is scraping the results, nobody's seeing the ads, and the ads are what pay for the whole thing.)
Of course nobody's forcing you to use Google. EntireWeb has an free "unlimited" (as in "as long as you don't use too much, and we haven't specified the limit") search API. Bing gives you a higher quota, and amortized by month instead of by day. Yahoo BOSS is flexible and super-cheap (and even offers a "discount server" that provides lower-quality results if it's not cheap enough), although I believe you're forced to type the ridiculous exclamation point. If none of them are good enough for you… then pay for Google.
I want to try to add all the step details - Expected, Actual, Status,
etc. to a QC Run for a testcase of a TestSet from a Python Script
living outside the Quality Center.
I have come till here (code given below) and I don't know how to add
Step Expected and Step Actual Result. If anyone knows how do it,
please help me out!! Please, I don't want any QTP solutions.
Thanks,
Code-
# Script name - add_tsrun.py
# C:\Python27\python.exe
# This script lives locally on a Windows machine that has - Python 2.7, Win32 installed, IE8
# Dependencies on Windows Machine - Python 2.7, PythonWin32 installed, IE8, a QC Account, connectivity to QCServer
import win32com.client, os
tdc = win32com.client.Dispatch("TDApiOle80.TDConnection")
tdc.InitConnection('http://QCSERVER:8080/qcbin')
tdc.Login('USERNAME', 'PASSWORD')
tdc.Connect('DOMAIN_NAME', 'PROJECT')
tsFolder = tdc.TestSetTreeManager.NodeByPath('Root\\test_me\\sub_folder')
tsList = tsFolder.FindTestSets('testset1')
ts_object = tsList.Item(1)
ts_dir = os.path.dirname('testset1')
ts_name = os.path.basename('testset1')
tsFolder = tdc.TestSetTreeManager.NodeByPath(ts_dir)
tsList = tsFolder.FindTestSets(ts_name)
ts_object = tsList.Item(1)
TSTestFact = ts_object.TSTestFactory
TestSetTestsList = TSTestFact.NewList("")
ts_instance = TestSetTestsList.Item(1)
newItem = ts_instance.RunFactory.AddItem(None) # newItem == Run Object
newItem.Status = 'No Run'
newItem.Name = 'Run 03'
newItem.Post()
newItem.CopyDesignSteps() # Copy Design Steps
newItem.Post()
steps = newItem.StepFactory.NewList("")
step1 = steps[0]
step1.Status = "Not Completed"
step1.post()
## How do I change the Actual Result??
## I can access the Actual, Expected Result by doing this, but not change it
step1.Field('ST_ACTUAL') = 'My actual result' # This works in VB, not python as its a Syntax error!!
Traceback ( File "<interactive input>", line 1
SyntaxError: can't assign to function call
Hope this helps you guys out there. If you know the answer to set the
Actual Result, please help me out and let me know. Thanks,
Amit
As Ethan Furman answered in your previous question:
In Python () represent calls to functions, while [] represent indexing and mapping.
So in other words, you probably want to do step1.Field['ST_ACTUAL'] = 'My actual result'
Found the answer after a lot of Google Search :)
Simple -> Just do this:
step1.SetField("ST_ACTUAL", "my actual result") # Wohhooooo!!!!
If the above code fails to work, try to do the following:-
(OPTIONAL) Set your win32 com as follows- (Making ''Late Binding'')
# http://oreilly.com/catalog/pythonwin32/chapter/ch12.html
a. Start PythonWin, and from the Tools menu, select the item COM Makepy utility.
b. Using Windows Explorer, locate the client subdirectory (OTA COM Type Library)
under the main win32com directory and double-click the file makepy.py.
Thank you all...