Python Updating system time - python

I have an application that is time sensitive to the time on a remote server - it needs to be run at a particular instant. Looping and retrieving the server time continuously does not get me as close as i'd like. I am trying to retrieve the server time and update my system's time (Python 3.7, windows 10) in advance so the module can restart as close as possible to the server's time. I have found the SetSysemTime function in win32api.
Here is the two line module i created to test various approaches:
import win32api
win32api.SetSystemTime(2020,9,1,21,9,10,10,0)
When i run this i get the following error:
Traceback (most recent call last):
File "C:\Users\pinev\AppData\Local\Programs\Python\Python37\Projects\Threading Tests\settime.py", line 4, in
win32api.SetSystemTime(2020,9,1,21,9,10,10,0)
pywintypes.error: (1314, 'SetSystemTime', 'A required privilege is not held by the client.')
So it seems i have the right solution, but somehow the module's privilege needs to be changed in order for Win10 to process the request. I have researched ways to set the privilege in a Python module and can't seem to find anything that works. If anyone could could provide a solution or a reference it would be greatly appreciated.
Thanks in advance.

If you just need to elevate privileges to run Python programs, you can launch the program as an administrator.
This is also the simplest and most direct method I think.
Test code:
import win32api
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
win32api.SetSystemTime(2020,9,1,21,9,10,10,0)
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)

Related

Why libvirt python module stopping my script?

So, I'm in process of learning python with libvirt module. Here is a little script that I made which checks if connection with libvirtd is successfully established and checks for one domain. I'm not developer and I'm taking some shortcuts so I don't understand how python or libvirt module works. But my real problem at this moment why is my script closing if connection is not established or domain is not found.
#!/usr/bin/env python3
from __future__ import print_function
import sys
import libvirt
domName = 'server1'
conn = libvirt.open('qemu:///system')
if conn == None:
print('Failed to open connection to qemu:///system', file=sys.stderr)
exit(1)
else:
print('Connection opened sucessfully')
dom = conn.lookupByName(domName)
if dom == None:
print('Failed to find the domain '+domName, file=sys.stderr)
exit(1)
else:
print('Domain '+domName+' was found')
conn.close()
exit(0)
For example libvirtd service is stopped and connection is not established and instead going further down the lines into if statement it just prints some errors and stops, so there is an if statement which should check for this, but like this it does not has any functionality. It looks like this
[root#localhost Documents]# ./virt.py
libvirt: XML-RPC error : Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory
Traceback (most recent call last):
File "./virt.py", line 11, in <module>
conn = libvirt.open('qemu:///system')
File "/usr/local/lib64/python3.6/site-packages/libvirt.py", line 277, in open
if ret is None:raise libvirtError('virConnectOpen() failed')
libvirt.libvirtError: Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory
[root#localhost Documents]#
I managed to suppress errors but then it just the same thing but without errors. Also I found this script here.
I found this script here (...)
Well, then you've learned one first lesson: you shouldn't rely on copy-pasting code found "here" (nor in most other places actually). Actually, you can consider that about 80% of the code you'll find on the net is crap (and I'm being generous).
I'm in process of learning python
Did you do the full official Python tutorial ? If no, then that's really what you want to start with (assuming you already get the basic concepts like types, variables, conditionals, iteration, functions, etc - else you want this instead)
For example libvirtd service is stopped and connection is not established and instead going further down the lines into if statement it just prints some errors and stops
Like most modern languages, Python uses a mechanism named "exceptions" to signal errors. This is much more powerful, usable and reliable than returning error codes or special values from functions...
This is all explained in the tutorial, so I won't bother posting corrected code, just following the tutorial should be enough to let you fix this code by yourself.
libvirt.libvirtError: Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory
This error message suggests that the libvirtd daemon is not actually running on this host.
Your script still needs changes though if you want to catch errors. libvirt APIs will raise exceptions when things go wrong, so instead of checking the return value against "None", you need a try/except block to catch & handle it

"Windows Error: provider DLL failed to initialize correctly" on import of cgi module in frozen wxpython app

I have a user of a frozen wxpython app that gets the appended screenshot.
The error message is "Windows Error: provider DLL failed to initialize correctly"
A screenshot taken from a paused video is the only way I could get this error message from them because the whole thing disappears instantly (including this DOS window created to capture stderr, where this message is appearing). IE python is dieing before it even really gets going.
The traceback points to my code at controller.py line 14.
This line is
import cgi
For some reason, it seems that cgi is calling random during import (why would that be?) and for some reason this is failing for some DLL reason.
Any clues?
Note 1: this app works fine for hundreds of other Windows and Mac users. So it's as if I'm not supplying something that is not on only this user's machine for some reason.
Note 2: the executable is created using bbfreeze, with the following config:
f = Freezer(distdir = distdir,
includes = ['wx.lib.pubsub.core.kwargs.*',
'wx.lib.pubsub.core.*',
'dbhash',
'platform']
)
I'm not sure what else I'd put in here. 'cgi'? 'random'?
For me, the exact error message was:
WindowsError: [Error -2146893795] Provider DLL failed to initialize correctly
with a trace such as:
File "C:\Dev\Python\python-2.7.11\lib\tempfile.py", line 35, in <module>
from random import Random as _Random
File "C:\Dev\Python\python-2.7.11\lib\random.py", line 885, in <module>
_inst = Random()
File "C:\Dev\Python\python-2.7.11\lib\random.py", line 97, in __init__
self.seed(x)
File "C:\Dev\Python\python-2.7.11\lib\random.py", line 113, in seed
a = long(_hexlify(_urandom(2500)), 16)
WindowsError: [Error -2146893795] Provider DLL failed to initialize correctly
And what solved it for me was a comment from http://bugs.python.org/issue1384175 (http://bugs.python.org/msg248947), saying the following:
This happened at a call to `os.urandom` for me.
This was in a subprocess.
The bug for me was that I called `_subprocess.CreateProcess`
with an `env_mapper = {'foo': 'bar'}`. The fix:
env_mapper = os.environ.copy()
env_mapper.update({'foo': 'bar'})
I think the minimal solution is to include the SYSTEMROOT environment variable in the Python subprocess.
I have seen the problem when trying to load os.urandom:
self._authkey = AuthenticationString(os.urandom(32))
WindowsError: [Error -2146893795] Provider DLL failed to initialize correctly
It turns out that the _PyOS_URandom on Windows relies on the SYSTEMROOT environment to be set. See: http://bugs.python.org/issue1384175#msg248951 for a detailed explaination
This seems to occur somewhere inside os.urandom and is probably caused by some missing or incorrect environment variables. In particular it happens if the environment is too long.
If you are starting Python from a shell, open a new shell and try again. If the problem persists, check if there are unusually many environment variables
If you are starting Python from another process, check if the proces environment is set up correctly. I found that this is often not the case for processes run by Apache's CGI module.
if you are starting Python as a CGI process, then you may want to consider better alternatives, such as mod_wsgi.

Qualcomm's QPST Automation Server in Python 2.7 using win32com module

Python newbie here. So, please excuse if this has been asked before in a different format.
I am trying to replicate the following perl snippet in Python using the win32com module. This snippet is provided by Qualcomm for easier automation of their tools.
use Win32::OLE;
use Win32::OLE::Variant;
$prod_id = "QPSTAtmnServer.Application"; # AppId for the Automation server.
eval{ $qpst = Win32::OLE->GetActiveObject($prod_id)}; # Attempt to use a running instance.
die "$prod_id not installed" if $#;
unless (defined $qpst) { $qpst = Win32::OLE->new($prod_id, sub {$_[0]->Quit;}) or die "Cannot start $prod_id";} # Start a new instance. Call Quit when $qpst set to undef or script exits.
if (defined $qpst)
{
$port = $qpst->GetPort("COM30001");
}
The block of python code I have till now is as follows:
import win32com.client
import time
import os
cmd = 'cls'
os.system(cmd)
cmd = 'start C:\\LAB\\exe\\pskill.exe QPSTConfig'
os.system(cmd)
cmd = 'start C:\\LAB\\exe\\pskill.exe QPSTServer'
os.system(cmd)
cmd = 'start C:\\LAB\\exe\\pskill.exe AtmnServer'
os.system(cmd)
time.sleep(2)
_path = os.getcwd()
qpst = win32com.client.Dispatch('QPSTAtmnServer.Application')
time.sleep(5)
if (qpst is None):
print('Darn!')
else:
port = qpst.GetPort('30001')
print(port)
and it throws the following error:
Traceback (most recent call last):
File "xxxx.py", line 20, in module
port = qpst.GetPort('30001')
TypeError: 'NoneType' object is not callable
After reading a couple of posts it seems like the method (GetPort) is not registering as a method after all.
Is that correct analysis?
If yes, how do I make Python interpret it as a method?
If not, what is going on here with the error?
Thanks in advance for the help!
It looks like I had to do couple of things to solve the issue.
Use the makepy command on the "AtmnServer" OLE TypeLibrary file to create a *.py file in:
...\Python27\Lib\site-packages\win32com\gen_py\
Add an extra line to actually interpret the required Method as a method (instead of as a property/attribute or something) :
qpst._FlagAsMethod("GetPort")
before the line:
port = qpst.GetPort("COM30001")
Thanks again for offering to help!
Correct, it is saying that GetPort does not exist. Have you checked that the Perl version works? If you don't have Perl, you could try through Excel's VBA (open its VBA console -- you may have to enable it by following the steps here). If you can dispath the QPST from Excel VBA and do the GetPort, then something is very odd.
It could be that QPST COM interface changed since this script was written. You could try
qpst = win32com.client.gencache.EnsureDispatch(
'QPSTAtmnServer.Application')
which will attempt to create the type library for QPST. Sometimes it finds extra objects, but if not at very least you can then browse the QPST COM from python using combrowse.py (which is part of pywin32) and try to find where that function is. Combrowse is a basic COM browser, just run \Lib\site-packages\win32com\client\combrowse.py, if need more powerful the one from visual studio is probably better.

Python and Pynotify error "gio.Error: Connection Closed"

i'm new on python and pynotify i want to create a notify message that shows me a notification with python and pynotify but i have a problem, all examples i use on tutorials found on internet.
ex.
#!/usr/bin/python
import sys
import pynotify
if __name__ == "__main__":
if not pynotify.init("icon-summary-body"):
sys.exit(1)
n = pynotify.Notification(
"Hi There",
"welcome to stackoverflow!",
##dont remove the below line
"notification-message-im")
n.show()
or
#!/usr/bin/env python
import os
import pynotify
pynotify.init("random information")
s = os.popen("fortune -n 100 -s","r").read()
n = pynotify.Notification("Fortune",s)
n.show()
gives me always the same error
** (icmp.py:13188): WARNING **: Connection Closed
Traceback (most recent call last):
File "icmp.py", line 14, in <module>
n.show()
gio.Error: Connection Closed
What does it mean??
Thanks
Well, I am responding you a year after posting this question. You may have already got the solution. So I will answer for other people facing the problem.
I was working on one project which uses Pynotify and I encountered the same problem. After a lot of research I found out that I was calling my script with root user. If you are also running your script with root user, then it may be the problem. The problem is that root does not have a dbus session running. I guess it does not even own XScreen. I assume you want to use Dbus session that belongs to the logged in user.
Solution 1: Use gksu. GUI applications should be started with gksu, not su or sudo.
Solution 2: Add following to your script.
import os
os.environ['DISPLAY'] = ':0.0'
Solution 3: Add root user to dbus group. [Not Verified]
I hope it helps.
To me the only way for now to use notification while using sudo python is by calling notify-send with subprocess:
Desktop environment: xfce4
WIP method (Insecure): sudo -Eu root python2.7
import os, subprocess
SudoUser = os.environ['SUDO_USER']
DBUSAddress = "DBUS_SESSION_BUS_ADDRESS={}".format(os.environ['DBUS_SESSION_BUS_ADDRESS'])
NotiCommand='{} notify-send "Welcome" "{}"'.format(DBUSAddress, SudoUser)
CompleteCall = 'sudo -u {} {}'.format(SudoUser, NotiCommand)
subprocess.call(CompleteCall, shell=True)
There you go! In my case this problem is the result of the tight security in Arch based distros as debian base distros are more flexible or actually insecure. Because this is more like a hack and it uses "shell=True" it's not recommended.
Sometimes this can happen when there is too long of a gap between calling .init() and creating the notification. There is a timeout, and when you call pynotify.init() that can elapse. If you make sure you call it again immediately before issuing the notification, you should quell this error.

Python tempfile module and threads aren't playing nice; what am I doing wrong?

I'm having an interesting problem with threads and the tempfile module in Python. Something doesn't appear to be getting cleaned up until the threads exit, and I'm running against an open file limit. (This is on OS X 10.5.8, Python 2.5.1.)
Yet if I sort of replicate what the tempfile module is doing (not all the security checks, but just generating a file descriptor and then using os.fdopen to produce a file object) I have no problems.
Before filing this as a bug with Python, I figured I'd check here, as it's much more likely that I'm doing something subtly wrong. But if I am, a day of trying to figure it out hasn't gotten me anywhere.
#!/usr/bin/python
import threading
import thread
import tempfile
import os
import time
import sys
NUM_THREADS = 10000
def worker_tempfile():
tempfd, tempfn = tempfile.mkstemp()
tempobj = os.fdopen(tempfd, 'wb')
tempobj.write('hello, world')
tempobj.close()
os.remove(tempfn)
time.sleep(10)
def worker_notempfile(index):
tempfn = str(index) + '.txt'
# The values I'm passing os.open may be different than tempfile.mkstemp
# uses, but it works this way as does using the open() function to create
# a file object directly.
tempfd = os.open(tempfn,
os.O_EXCL | os.O_CREAT | os.O_TRUNC | os.O_RDWR)
tempobj = os.fdopen(tempfd, 'wb')
tempobj.write('hello, world')
tempobj.close()
os.remove(tempfn)
time.sleep(10)
def main():
for count in range(NUM_THREADS):
if count % 100 == 0:
print('Opening thread %s' % count)
wthread = threading.Thread(target=worker_tempfile)
#wthread = threading.Thread(target=worker_notempfile, args=(count,))
started = False
while not started:
try:
wthread.start()
started = True
except thread.error:
print('failed starting thread %s; sleeping' % count)
time.sleep(3)
if __name__ == '__main__':
main()
If I run it with the worker_notempfile line active and the worker_tempfile line commented-out, it runs to completion.
The other way around (using worker_tempfile) I get the following error:
$ python threadtempfiletest.py
Opening thread 0
Opening thread 100
Opening thread 200
Opening thread 300
Exception in thread Thread-301:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 460, in __bootstrap
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py", line 440, in run
File "threadtempfiletest.py", line 17, in worker_tempfile
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py", line 302, in mkstemp
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py", line 236, in _mkstemp_inner
OSError: [Errno 24] Too many open files: '/var/folders/4L/4LtD6bCvEoipksvnAcJ2Ok+++Tk/-Tmp-/tmpJ6wjV0'
Any ideas what I'm doing wrong? Is this a bug in Python, or am I being bone-headed?
UPDATE 2009-12-14:
I think I've found the answer, but I don't like it. Since nobody was able to replicate the problem, I went hunting around our office for machines. It passed on everything except my machine. I tested on a Mac with the same software versions I was using. I even went hunting for a Desktop G5 with the EXACT same hardware and software config I had -- same result. Both tests (with tempfile and without tempfile) succeeded on everything.
For kicks, I downloaded Python 2.6.4, and tried it on my desktop, and same pattern on my system as Python 2.5.1: tempfile failed, and notempfile succeeded.
This is leading me to the conclusion that something's hosed on my Mac, but I sure can't figure out what. Any suggestions are welcome.
I am unable to reproduce the problem with (Apple's own build of) Python 2.5.1 on Mac OS X 10.5.9 -- runs to completion just fine!
I've tried both on a Macbook Pro, i.e., an Intel processor, and an old PowerMac, i.e., a PPC processor.
So I can only imagine there must have been a bug in 10.5.8 which I never noticed (don't have any 10.5.8 around to test, as I always upgrade promptly whenever software update offers it). All I can suggest is that you try upgrading to 10.5.9 and see if the bug disappears -- if it doesn't, I have no idea how this behavior difference between my machines and yours is possible.
I think your answer can be found here. You have to explicitly os.close() the file descriptor given as the first part of the tuple that mkstemp gives you.
Edit: no, the OP is already doing what is supposed to be done. I'm leaving the answer up for the nice link.
I just tested your code on my Ubuntu Linux computer here, and it worked perfectly for me.
I have one suggestion for you to try. I don't know that it will help but it can't hurt. Rewrite your code to use with:
from __future__ import with_statement
def worker_tempfile():
tempfd, tempfn = tempfile.mkstemp()
with os.fdopen(tempfd, 'wb') as tempobj:
tempobj.write('hello, world')
os.remove(tempfn)
time.sleep(10)
The with statement is supposed to make sure that the file object gets closed no matter what. Perhaps it might help?
Good luck. Great job on the question, by the way.
Why do you think the error is not genuine? You are launching 10000 threads, each opening a file, while the maximum number of open files is typically 1024 under Unix systems.
First try to keep manually track of the number of files currently open and check whether it bumps past the OS limit.
Since nobody was able to replicate the problem, I went hunting around our office for machines. It passed on everything except my machine. I tested on a Mac with the same software versions I was using. I even went hunting for a Desktop G5 with the EXACT same hardware and software config I had -- same result. Both tests (with tempfile and without tempfile) succeeded on everything.
For kicks, I downloaded Python 2.6.4, and tried it on my desktop, and same pattern on my system as Python 2.5.1: tempfile failed, and notempfile succeeded.
This is leading me to the conclusion that something's hosed on my Mac, so this isn't likely to be a problem that anyone else runs into ever.
Thanks VERY much to everyone (especially Alex Martelli) who helped on this!

Categories