Python GI Notify How can I call the Gtk.main()? - python

I'm trying to create a Python notification application. To make it short here is what I wanted to do :
1. Checking my gmail account
2. Display a notification with the number of unread mails
3. Display a button that permits me to open chromium (using a system call)
For now everything looks just fine. The checking mail part was kind of easy. I serialised my unread mail count so that the notification doesn't show up every single minute. It only displays if I have a new mail.
Where I'm blocking is that I don't know how to create the main gtk loop so that I can handle the button signal.
Here is my code :
#!/usr/bin/python
from gi.repository import Notify, Gtk, GLib
from urllib.request import FancyURLopener
from datetime import datetime, date, time, timedelta
import os.path, sys, getopt
from subprocess import call
serialisedvalue=0;
serialiseddate=0;
def callback():
call(["chromium", "gmail.com"])
def serialise(unread):
try:
f = open("mailcount", "w")
try:
f.write(unread+"\n") # Write a string to a file
f.write(datetime.now().strftime('%b %d %Y %I:%M%p'))
finally:
f.close()
except IOError:
pass
def deserialise():
global serialisedvalue
global serialiseddate
try:
f = open("mailcount", "r")
try:
serialisedvalue = f.readline().rstrip()
serialiseddate = datetime.strptime(f.readline(), '%b %d %Y %I:%M%p')
finally:
f.close()
except IOError:
pass
def notif(unread):
Notify.init ("New Mail")
if unread != "1":
Hello=Notify.Notification.new ("New mail","You have "+unread+" unread mails","/usr/share/icons/Faenza/actions/96/mail-forward.png")
else :
Hello=Notify.Notification.new ("New mail","You have "+unread+" unread mails","/usr/share/icons/Faenza/actions/96/mail-forward.png")
Hello.add_action('action', 'Read', callback, None, None)
Hello.show ()
def main(argv):
notify=0
forced=0
try:
opts, args = getopt.getopt(argv,"nf",['notify','force-notify'])
except getopt.GetoptError:
print("unreadgmail.py [-n --notify] [-f --force-notify")
sys.exit(2)
for opt,args in opts:
if opt in ("-n", "--notify"):
notify=1
elif opt in ("-f","--force-notify"):
forced=1
url = 'https://%s:%s#mail.google.com/mail/feed/atom' % ("myaccount", "mypassword")
opener = FancyURLopener()
page = opener.open(url)
contents = page.read().decode('utf-8')
ifrom = contents.index('<fullcount>') + 11
ito = contents.index('</fullcount>')
unread = contents[ifrom:ito]
print("Unread messages : "+unread)
if notify==1 and forced==0:
if os.path.exists("mailcount"):
deserialise()
else:
serialise(unread)
deserialise()
if unread != "0":
if unread != serialisedvalue:
notif(unread)
serialise(unread)
elif ((datetime.now() - serialiseddate) > timedelta(hours=1)):
notif(unread)
if forced==1:
notif(unread)
GLib.MainLoop().run()
if __name__ == "__main__":
main(sys.argv[1:])
I remember that my notifications used to work fine with pygtk and pynotify. Though I want to update my code and since I lost the last code, I don't have a clue on that. Calling Gtk.main() in my main just block the program until I kill it.
I'm using Gnome3.6, Archlinux and python3.3.
So does anyone know how to "wait" for the signal handler to be clicked before the program ends ? In fact it runs fine, but the script just end when the notification is displayed and it doesn't wait for the signal.
Thanks a lot :)
EDIT : A bit more details of my problem :
As you can see, the program already ended and is not waiting for a signal. That's what I'm trying to solve right now.

If you're not using GTK+--which as far as I can tell you aren't--you could probably call GLib.MainLoop().run() at the end of your main function to keep your program running.

Related

You do not have permission to open this file' when using os.system() [duplicate]

I am writing a pyqt application which require to execute admin task. I would prefer to start my script with elevate privilege. I am aware that this question is asked many times in SO or in other forum. But the solution people are suggesting is to have a look at this SO question
Request UAC elevation from within a Python script?
However, I am unable to execute the sample code given in the link. I have put this code on top of the main file and tried to execute it.
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)
print "I am root now."
It actually ask permission to elevate but print line never get executed. Somebody can help me to run the above code successfully.
Update as on 19-02-2023
The update to the below script is now alive as a Python package by the same author. You can install it from PyPi which lives at https://pypi.org/project/pyuac/ and the source code/ home page is located at https://github.com/Preston-Landers/pyuac. Install it using:
pip install pyuac
Direct usage of the package is:
import pyuac
def main():
print("Do stuff here that requires being run as an admin.")
# The window will disappear as soon as the program exits!
input("Press enter to close the window. >")
if __name__ == "__main__":
if not pyuac.isUserAdmin():
print("Re-launching as admin!")
pyuac.runAsAdmin()
else:
main() # Already an admin here.
or if you wish to use it using decorater:
from pyuac import main_requires_admin
#main_requires_admin
def main():
print("Do stuff here that requires being run as an admin.")
# The window will disappear as soon as the program exits!
input("Press enter to close the window. >")
if __name__ == "__main__":
main()
Original answer
Thank you all for your reply. I got my script working with the module/ script written by Preston Landers in 2010. After two days of browsing the internet, I could find the script as it was deeply hidden in the pywin32 mailing list. With this script, it is easier to check if the user is admin, and if not then ask for UAC/ admin right. It does provide output in separate windows to find out what the code is doing. An example of how to use the code is also included in the script. For the benefit of all who are looking for UAC on windows have a look at this code. I hope it helps someone looking for the same solution. It can be used something like this from your main script:-
import admin
if not admin.isUserAdmin():
admin.runAsAdmin()
The actual code is:-
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
# (C) COPYRIGHT © Preston Landers 2010
# Released under the same license as Python 2.6.5
import sys, os, traceback, types
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print "Admin check failed, assuming not an admin."
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
raise RuntimeError, "Unsupported operating system for this module: %s" % (os.name,)
def runAsAdmin(cmdLine=None, wait=True):
if os.name != 'nt':
raise RuntimeError, "This function is only implemented on Windows."
import win32api, win32con, win32event, win32process
from win32com.shell.shell import ShellExecuteEx
from win32com.shell import shellcon
python_exe = sys.executable
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif type(cmdLine) not in (types.TupleType,types.ListType):
raise ValueError, "cmdLine is not a sequence."
cmd = '"%s"' % (cmdLine[0],)
# XXX TODO: isn't there a function or something we can call to massage command line params?
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
cmdDir = ''
showCmd = win32con.SW_SHOWNORMAL
#showCmd = win32con.SW_HIDE
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=shellcon.SEE_MASK_NOCLOSEPROCESS,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = None
return rc
def test():
rc = 0
if not isUserAdmin():
print "You're not an admin.", os.getpid(), "params: ", sys.argv
#rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()
else:
print "You are an admin!", os.getpid(), "params: ", sys.argv
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())
in comments to the answer you took the code from someone says ShellExecuteEx doesn't post its STDOUT back to the originating shell. so you will not see "I am root now", even though the code is probably working fine.
instead of printing something, try writing to a file:
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)
with open("somefilename.txt", "w") as out:
print >> out, "i am root"
and then look in the file.
I found a very easy solution to this problem.
Create a shortcut for python.exe
Change the shortcut target into something like C:\xxx\...\python.exe your_script.py
Click "advance..." in the property panel of the shortcut, and click the option "run as administrator"
I'm not sure whether the spells of these options are right, since I'm using Chinese version of Windows.
Here is a solution which needed ctypes module only. Support pyinstaller wrapped program.
#!python
# coding: utf-8
import sys
import ctypes
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
arguments = map(unicode, argv[1:])
else:
arguments = map(unicode, argv)
argument_line = u' '.join(arguments)
executable = unicode(sys.executable)
if debug:
print 'Command line: ', executable, argument_line
ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
if int(ret) <= 32:
return False
return None
if __name__ == '__main__':
ret = run_as_admin()
if ret is True:
print 'I have admin privilege.'
raw_input('Press ENTER to exit.')
elif ret is None:
print 'I am elevating to admin privilege.'
raw_input('Press ENTER to exit.')
else:
print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
Here is a solution with an stdout redirection:
def elevate():
import ctypes, win32com.shell.shell, win32event, win32process
outpath = r'%s\%s.out' % (os.environ["TEMP"], os.path.basename(__file__))
if ctypes.windll.shell32.IsUserAnAdmin():
if os.path.isfile(outpath):
sys.stderr = sys.stdout = open(outpath, 'w', 0)
return
with open(outpath, 'w+', 0) as outfile:
hProc = win32com.shell.shell.ShellExecuteEx(lpFile=sys.executable, \
lpVerb='runas', lpParameters=' '.join(sys.argv), fMask=64, nShow=0)['hProcess']
while True:
hr = win32event.WaitForSingleObject(hProc, 40)
while True:
line = outfile.readline()
if not line: break
sys.stdout.write(line)
if hr != 0x102: break
os.remove(outpath)
sys.stderr = ''
sys.exit(win32process.GetExitCodeProcess(hProc))
if __name__ == '__main__':
elevate()
main()
It worth mentioning that if you intend to package your application with PyInstaller and wish to avoid supporting that feature by yourself, you can pass the --uac-admin or --uac-uiaccess argument in order to request UAC elevation on start.
make a batch file
add python.exe "(your py file here)" with the quotation marks
save the batch file
right click, then click run as administrator
Also if your working directory is different than you can use lpDirectory
procInfo = ShellExecuteEx(nShow=showCmd,
lpVerb=lpVerb,
lpFile=cmd,
lpDirectory= unicode(direc),
lpParameters=params)
Will come handy if changing the path is not a desirable option
remove unicode for python 3.X
This worked for me:
import win32com.client as client
required_command = "cmd" # Enter your command here
required_password = "Simple1" # Enter your password here
def run_as(required_command, required_password):
shell = client.Dispatch("WScript.shell")
shell.Run(f"runas /user:administrator {required_command}")
time.sleep(1)
shell.SendKeys(f"{required_password}\r\n", 0)
if __name__ = '__main__':
run_as(required_command, required_password)
Below are the references I used for above code:
https://win32com.goermezer.de/microsoft/windows/controlling-applications-via-sendkeys.html
https://www.oreilly.com/library/view/python-cookbook/0596001673/ch07s16.html
Use pyuac
it is the update to the orignal admin Script by Preston Landers
Link to python Projects: https://pypi.org/project/pyuac/
Github: https://github.com/Preston-Landers/pyuac
This worked for me it
from pyuac import main_requires_admin
#main_requires_admin
def main():
print("Do stuff here that requires being run as an admin.")
# The window will disappear as soon as the program exits!
input("Press enter to close the window. >")
if __name__ == "__main__":
main()
JetBrains' WinElevator (signed elevator.exe and launcher.exe available here) allows you to spawn a subprocess that requests elevated privileges while keeping stdin/stdout/stderr intact:
import ctypes
import subprocess
import sys
if not ctypes.windll.shell32.IsUserAnAdmin():
print("not an admin, restarting...")
subprocess.run(["launcher.exe", sys.executable, *sys.argv])
else:
print("I'm an admin now.")
> python example.py
not an admin, restarting...
# UAC prompt is shown
I'm an admin now.
I can confirm that the solution by delphifirst works and is the easiest, simplest solution to the problem of running a python script with elevated privileges.
I created a shortcut to the python executable (python.exe) and then modified the shortcut by adding my script's name after the call to python.exe. Next I checked "run as administrator" on the "compatibility tab" of the shortcut. When the shortcut is executed, you get a prompt asking permission to run the script as an administrator.
My particular python application was an installer program. The program allows installing and uninstalling another python app. In my case I created two shortcuts, one named "appname install" and the other named "appname uninstall". The only difference between the two shortcuts is the argument following the python script name. In the installer version the argument is "install". In the uninstall version the argument is "uninstall". Code in the installer script evaluates the argument supplied and calls the appropriate function (install or uninstall) as needed.
I hope my explanation helps others more quickly figure out how to run a python script with elevated privileges.
Make sure you have python in path,if not,win key + r, type in "%appdata%"(without the qotes) open local directory, then go to Programs directory ,open python and then select your python version directory. Click on file tab and select copy path and close file explorer.
Then do win key + r again, type control and hit enter. search for environment variables. click on the result, you will get a window. In the bottom right corner click on environmental variables. In the system side find path, select it and click on edit.
In the new window, click on new and paste the path in there. Click ok and then apply in the first window. Restart your PC. Then do win + r for the last time, type cmd and do ctrl + shift + enter. Grant the previliges and open file explorer, goto your script and copy its path. Go back into cmd , type in "python" and paste the path and hit enter. Done
I wanted a more enhanced version so I ended up with a module which allows:
UAC request if needed, printing and logging from nonprivileged instance (uses ipc and a network port) and some other candies. usage is just insert elevateme() in your script: in nonprivileged it listen for privileged print/logs and then exits returning false, in privileged instance it returns true immediately.
Supports pyinstaller.
prototype:
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
winadmin.py
#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4
# (C) COPYRIGHT © Preston Landers 2010
# (C) COPYRIGHT © Matteo Azzali 2020
# Released under the same license as Python 2.6.5/3.7
import sys, os
from traceback import print_exc
from multiprocessing.connection import Listener, Client
import win32event #win32com.shell.shell, win32process
import builtins as __builtin__ # python3
# debug suffixes for remote printing
dbz=["","","",""] #["J:","K:", "G:", "D:"]
LOGTAG="LOGME:"
wrconn = None
#fake logger for message sending
class fakelogger:
def __init__(self, xlogger=None):
self.lg = xlogger
def write(self, a):
global wrconn
if wrconn is not None:
wrconn.send(LOGTAG+a)
elif self.lg is not None:
self.lg.write(a)
else:
print(LOGTAG+a)
class Writer():
wzconn=None
counter = 0
def __init__(self, tport=6000,authkey=b'secret password'):
global wrconn
if wrconn is None:
address = ('localhost', tport)
try:
wrconn = Client(address, authkey=authkey)
except:
wrconn = None
wzconn = wrconn
self.wrconn = wrconn
self.__class__.counter+=1
def __del__(self):
self.__class__.counter-=1
if self.__class__.counter == 0 and wrconn is not None:
import time
time.sleep(0.1) # slows deletion but is enough to print stderr
wrconn.send('close')
wrconn.close()
def sendx(cls, mesg):
cls.wzconn.send(msg)
def sendw(self, mesg):
self.wrconn.send(msg)
#fake file to be passed as stdout and stderr
class connFile():
def __init__(self, thekind="out", tport=6000):
self.cnt = 0
self.old=""
self.vg=Writer(tport)
if thekind == "out":
self.kind=sys.__stdout__
else:
self.kind=sys.__stderr__
def write(self, *args, **kwargs):
global wrconn
global dbz
from io import StringIO # # Python2 use: from cStringIO import StringIO
mystdout = StringIO()
self.cnt+=1
__builtin__.print(*args, **kwargs, file=mystdout, end = '')
#handles "\n" wherever it is, however usually is or string or \n
if "\n" not in mystdout.getvalue():
if mystdout.getvalue() != "\n":
#__builtin__.print("A:",mystdout.getvalue(), file=self.kind, end='')
self.old += mystdout.getvalue()
else:
#__builtin__.print("B:",mystdout.getvalue(), file=self.kind, end='')
if wrconn is not None:
wrconn.send(dbz[1]+self.old)
else:
__builtin__.print(dbz[2]+self.old+ mystdout.getvalue(), file=self.kind, end='')
self.kind.flush()
self.old=""
else:
vv = mystdout.getvalue().split("\n")
#__builtin__.print("V:",vv, file=self.kind, end='')
for el in vv[:-1]:
if wrconn is not None:
wrconn.send(dbz[0]+self.old+el)
self.old = ""
else:
__builtin__.print(dbz[3]+self.old+ el+"\n", file=self.kind, end='')
self.kind.flush()
self.old=""
self.old=vv[-1]
def open(self):
pass
def close(self):
pass
def flush(self):
pass
def isUserAdmin():
if os.name == 'nt':
import ctypes
# WARNING: requires Windows XP SP2 or higher!
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
traceback.print_exc()
print ("Admin check failed, assuming not an admin.")
return False
elif os.name == 'posix':
# Check for root on Posix
return os.getuid() == 0
else:
print("Unsupported operating system for this module: %s" % (os.name,))
exit()
#raise (RuntimeError, "Unsupported operating system for this module: %s" % (os.name,))
def runAsAdmin(cmdLine=None, wait=True, hidden=False):
if os.name != 'nt':
raise (RuntimeError, "This function is only implemented on Windows.")
import win32api, win32con, win32process
from win32com.shell.shell import ShellExecuteEx
python_exe = sys.executable
arb=""
if cmdLine is None:
cmdLine = [python_exe] + sys.argv
elif not isinstance(cmdLine, (tuple, list)):
if isinstance(cmdLine, (str)):
arb=cmdLine
cmdLine = [python_exe] + sys.argv
print("original user", arb)
else:
raise( ValueError, "cmdLine is not a sequence.")
cmd = '"%s"' % (cmdLine[0],)
params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
if len(arb) > 0:
params += " "+arb
cmdDir = ''
if hidden:
showCmd = win32con.SW_HIDE
else:
showCmd = win32con.SW_SHOWNORMAL
lpVerb = 'runas' # causes UAC elevation prompt.
# print "Running", cmd, params
# ShellExecute() doesn't seem to allow us to fetch the PID or handle
# of the process, so we can't get anything useful from it. Therefore
# the more complex ShellExecuteEx() must be used.
# procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)
procInfo = ShellExecuteEx(nShow=showCmd,
fMask=64,
lpVerb=lpVerb,
lpFile=cmd,
lpParameters=params)
if wait:
procHandle = procInfo['hProcess']
obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
rc = win32process.GetExitCodeProcess(procHandle)
#print "Process handle %s returned code %s" % (procHandle, rc)
else:
rc = procInfo['hProcess']
return rc
# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
global dbz
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
import getpass
uname = getpass.getuser()
if (tport> 0):
address = ('localhost', tport) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey=b'secret password')
rc = runAsAdmin(uname, wait=False, hidden=True)
if (tport> 0):
hr = win32event.WaitForSingleObject(rc, 40)
conn = listener.accept()
print ('connection accepted from', listener.last_accepted)
sys.stdout.flush()
while True:
msg = conn.recv()
# do something with msg
if msg == 'close':
conn.close()
break
else:
if msg.startswith(dbz[0]+LOGTAG):
if xlogger != None:
xlogger.write(msg[len(LOGTAG):])
else:
print("Missing a logger")
else:
print(msg)
sys.stdout.flush()
listener.close()
else: #no port connection, its silent
WaitForSingleObject(rc, INFINITE);
return False
else:
#redirect prints stdout on master, errors in error.txt
print("HIADM")
sys.stdout.flush()
if (tport > 0) and (redir):
vox= connFile(tport=tport)
sys.stdout=vox
if not errFile:
sys.stderr=vox
else:
vfrs=open("errFile.txt","w")
sys.stderr=vfrs
#print("HI ADMIN")
return True
def test():
rc = 0
if not isUserAdmin():
print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
sys.stdout.flush()
#rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
rc = runAsAdmin()
else:
print ("You are an admin!", os.getpid(), "params: ", sys.argv)
rc = 0
x = raw_input('Press Enter to exit.')
return rc
if __name__ == "__main__":
sys.exit(test())

Prevent Command Line Usage During Function Run in Python/Terminal?

I'm using Terminal to run a python script with a series of print statements, separated by the time.sleep function.
If I'm printing various items over a period of 10 seconds, I would like to be able to prevent the user from inputting new commands into the command line during this time.
Is this possible in Terminal? Is there a work-around?
My goal here is to be able to provide the user with a lot of print statements, then have them answer a question only after the question is asked.
Because I don't want to overwhelm the user, I want to time delay the print statements so it appears more manageable (well, it's really for theatrical effect).
ie
for i in range(10):
print "Eating cheeseburger..."
time.sleep(1)
response = raw_input("What is your favorite color?")
if response == "blue":
blah blah blah etc.
Right now, the user can input a response before the question is asked, and while the cheeseburger is still being eaten. I want to prevent this.
The question is a platform specific one, as different operating systems handle standard input and output differently. I will attempt to answer your question for Linux:
You can use os.system to access the linux command stty -echo to make any text entered on the terminal invisible, and stty echo to make it visible again.
The next thing you want to achieve is to clear the stdin buffer when user input is asked. This can be achieved through the termios function tcflush that can be used to flush all input that has been received but not read by the terminal yet.
import os
import time
import termios
import sys
os.system("stty -echo")
for i in range(10):
print(i)
time.sleep(1)
os.system("stty echo")
termios.tcflush(sys.stdin, termios.TCIOFLUSH)
print(raw_input("Answer now:"))
The following is a version of Saurabh Shirodkar's answer written for the Windows console using ctypes.
import sys
import msvcrt
import ctypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
ENABLE_ECHO_INPUT = 0x0004
def _check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
kernel32.GetConsoleMode.errcheck = _check_bool
kernel32.GetConsoleMode.argtypes = (ctypes.c_void_p,
ctypes.POINTER(ctypes.c_ulong))
kernel32.SetConsoleMode.errcheck = _check_bool
kernel32.SetConsoleMode.argtypes = (ctypes.c_void_p, ctypes.c_ulong)
kernel32.FlushConsoleInputBuffer.errcheck = _check_bool
kernel32.FlushConsoleInputBuffer.argtypes = (ctypes.c_void_p,)
def echo_input(enable=True, conin=sys.stdin):
h = msvcrt.get_osfhandle(conin.fileno())
mode = ctypes.c_ulong()
kernel32.GetConsoleMode(h, ctypes.byref(mode))
if enable:
mode.value |= ENABLE_ECHO_INPUT
else:
mode.value &= ~ENABLE_ECHO_INPUT
kernel32.SetConsoleMode(h, mode)
def flush_input(conin=sys.stdin):
h = msvcrt.get_osfhandle(conin.fileno())
kernel32.FlushConsoleInputBuffer(h)
if __name__ == '__main__':
import time
if sys.version_info[0] == 2:
input = raw_input
echo_input(False)
for i in range(10):
print(i)
time.sleep(1)
echo_input(True)
flush_input()
print(input("Answer now: "))

check if input is available on stdin with timeout

I have a python script that publishes messages that are read from stdin onto a message queue in the network. However, if there wasn't any message on the pipe for a specified amount of time I have to send a heartbeat.
So I have to distinguish between 3 cases:
There is input on the pipe that can be processed
There was no input for some specified amount of time
The piping process has been closed and we can gracefully terminate.
Currently, my code looks as follow:
import sys
for i, line in enumerate(sys.stdin):
connection.publish(line)
connection.close()
However I need to interrupt the for look if there was any timeout. I.e. sys.stdin has not delivered any data for some time.
This is what I finally came up with
import sys
import select
while True:
try:
if select.select([sys.stdin,],[],[],2.0)[0]:
line = sys.stdin.next()
print "Got:", line
else:
print "No data for 2 secs"
except StopIteration:
print 'EOF!'
break
If anybody is looking for a portable solution, this is what I came up with
after lots of trial and error.
It requires the pywin32 pypi package to work on windows
import os, sys
def is_windows() -> bool:
return os.name == "nt"
if is_windows():
import win32api, win32event, win32file, pywintypes
else:
import select
def stdin_has_content(timeout: float) -> bool:
assert timeout >= 0
if is_windows():
try:
# without this the wait might return despite there not being any input
win32file.FlushFileBuffers(win32api.STD_INPUT_HANDLE)
except pywintypes.error:
# this sometimes fails, but we don't mind
pass
return win32event.WaitForSingleObject(
win32api.STD_INPUT_HANDLE, int(timeout * 1000)
) == win32event.WAIT_OBJECT_0
else:
rlist, _, _ = select.select(
[sys.stdin], [], [], timeout
)
return bool(rlist)

reading output from pexpect sendline

I have pexpect working, but I am having problems printing the output back from it. In my test script below, it creates the ssh connection, and then sends a sudo su -, then my password, and then sends a line that would require sudo access to do (I have also added p.interact() a few times to make sure it is at root). The problem I am having, is with returning the output of the commands I run. In the end I am wanting to run some top commands, and some du -h, and other(much more complex) space commands. But currently when it tries to print p.before, I get:
Traceback (most recent call last):
File "./ssh.py", line 37, in <module>
print p.before()
TypeError: 'str' object is not callable
Here is the script I am working from(edited to remove my pass and such)
#!/usr/bin/env python
import pexpect
import struct, fcntl, os, sys, signal
def sigwinch_passthrough (sig, data):
# Check for buggy platforms (see pexpect.setwinsize()).
if 'TIOCGWINSZ' in dir(termios):
TIOCGWINSZ = termios.TIOCGWINSZ
else:
TIOCGWINSZ = 1074295912 # assume
s = struct.pack ("HHHH", 0, 0, 0, 0)
a = struct.unpack ('HHHH', fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ , s))
global global_pexpect_instance
global_pexpect_instance.setwinsize(a[0],a[1])
ssh_newkey = 'Are you sure you want to continue connecting'
p=pexpect.spawn('ssh user#localhost')
i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
print "I give password",
p.sendline("mypassword")
elif i==2:
print "I either got key or connection timeout"
pass
elif i==3: #timeout
pass
global global_pexpect_instance
global_pexpect_instance = p
p.sendline("sudo su -")
p.sendline("mypasswd")
p.sendline("mkdir /home/user/test")
print p.before
I am working off of this link: http://linux.byexamples.com/archives/346/python-how-to-access-ssh-with-pexpect/
Any help is much appreciated.
EDIT: As Armin Rigo pointed out below. I was calling to p.before as a function like p.before(). Stupid mistake on my part, as this explains why I was getting this error today, and not yesterday when I was trying this. After making that change to my script, and modifying the command being sent, print p.before, and no output is returned. Any other ways to return output from a sendline() command?
Use logfile, that logfile is store all output in terminal.use that example code:-
child = pexpect.spawn("ssh user#localhost")
child.logfile = open("/tmp/mylog", "w")
child.expect(".*assword:")
child.send("guest\r")
child.expect(".*\$ ")
child.sendline("python -V\r")
open the log file and see everything in terminals event
To fetch the complete output after sendline use child.read()
e.g.
cmd_resp = pexpect.spawnu(cmd) # for execution of the command
str_to_search = 'Please Enter The Password'
cmd_resp.sendline('yes') # for sending the input 'yes'
resp = cmd_resp.expect([str_to_search, 'password:', EOF], timeout=30) # fetch the output status
if resp == 1:
cmd_resp.sendline(password)
resp = cmd_resp.expect([str_to_search, 'outputString:', EOF], timeout=30)
print(cmd_resp.read()) # to fetch the complete output log
p.before is a string - not a function. To see the output you have to write
print p.before.
Hope this might help you

Python script run via cron does not execute occassionally

I have a simple python script for fetching tweets and caching them to disk that is configured to run every two minutes via cron.
*/2 * * * * (date ; /usr/bin/python /path/get_tweets.py) >> /path/log/get_tweets.log 2>&1
The script runs successfully most of the time. However, every so often the script doesn't execute. In addition to other logging, I added a simple print statement above the meat of the script and nothing except the output from the initial date command makes it to the log.
#!/usr/bin/python
# Script for Fetching Tweets and then storing them as an HTML snippet for inclusion using SSI
print "Starting get_tweets.py"
import simplejson as json
import urllib2
import httplib
import re
import calendar
import codecs
import os
import rfc822
from datetime import datetime
import time
import sys
import pprint
debug = True
now = datetime.today()
template = u'<p class="tweet">%s <span class="date">on %s</span></p>'
html_snippet = u''
timelineUrl = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=gcorne&count=7'
tweetFilePath = '/path/server-generated-includes/tweets.html'
if(debug): print "[%s] Fetching tweets from %s." % (now, timelineUrl)
def getTweets():
request = urllib2.Request(timelineUrl)
opener = urllib2.build_opener()
try:
tweets = opener.open(request)
except:
print "[%s] HTTP Request %s failed." % (now, timelineUrl)
exitScript()
tweets = tweets.read()
return tweets
def exitScript():
print "[%s] Script failed." % (now)
sys.exit(0)
tweets = getTweets()
now = datetime.today()
if(debug): print "[%s] Tweets retrieved." % (now)
tweets = json.loads(tweets)
for tweet in tweets:
text = tweet['text'] + ' '
when = tweet['created_at']
when = re.match(r'(\w+\s){3}', when).group(0).rstrip()
# print GetRelativeCreatedAt(when)
# convert links
text = re.sub(r'(http://.*?)\s', r'\1', text).rstrip()
#convert hashtags
text = re.sub(r'#(\w+)', r'#\1', text)
# convert # replies
text = re.sub(r'#(\w+)', r'#\1', text)
html_snippet += template % (text, when) + "\n"
#print html_snippet
now = datetime.today()
if(debug): print "[%s] Opening file %s." % (now, tweetFilePath)
try:
file = codecs.open(tweetFilePath, 'w', 'utf_8')
except:
print "[%s] File %s cound not be opened." % (now, tweetFilePath)
exitScript()
now = datetime.today()
if(debug): print "[%s] Writing %s to disk." % (now, tweetFilePath)
file.write(html_snippet)
now = datetime.today()
if(debug): print "[%s] Finished writing %s to disk." % (now, tweetFilePath)
file.close()
sys.exit(0)
Any ideas? The system is a VPS running Centos 5.3 with python 2.4.
Update: I have added the entire script to avoid any confusion.
The most likely explanation is that once in a while the script takes more than two minutes (maybe the system's very busy occasionally, or the script may have to wait for some external site that's occasionally busy, etc) and your cron's a sensible one that skips repeating events that haven't yet terminated. By logging the starting and ending times of your script, you'll be able to double check if that is the case. What you want to do in such circumstances is up to you (I recommend you consider skipping an occasional run to avoid further overloading a very busy system -- your own, or the remote one you're getting data from).
I just had a problem with a Python script which sometimes wouldn't run in crontab, but always ran from the command line. Turns out I had to redirect logging to /dev/null. The standard output otherwise seems to get full and the program just stops and the process is killed off. Using /dev/null to dump the output, and everything's fine.

Categories

Resources