<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Mouse Vs. The Python &#187; Windows</title>
	<atom:link href="http://www.blog.pythonlibrary.org/tag/windows/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.blog.pythonlibrary.org</link>
	<description>Python Programming from the Frontlines</description>
	<lastBuildDate>Sun, 08 Jan 2012 12:45:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Python 101: Setting up Python on Windows</title>
		<link>http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/</link>
		<comments>http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/#comments</comments>
		<pubDate>Thu, 24 Nov 2011 15:32:38 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[PyWin32]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=2052</guid>
		<description><![CDATA[Python is pretty easy to install on Windows, but sometimes you need to do a few extra tweaks to really get the most our your development environment. In this article, we will try to cover all the common things you might want to do or install to get an ideal Python Windows development workspace set [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/" data-url="http://bit.ly/tTCkmJ" data-text="Python 101: Setting up Python on Windows" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/";
			reddit_title = "Python 101: Setting up Python on Windows";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/"></g:plusone></div></div><p>Python is pretty easy to install on Windows, but sometimes you need to do a few extra tweaks to really get the most our your development environment. In this article, we will try to cover all the common things you might want to do or install to get an ideal Python Windows development workspace set up. Some of you might think that all you need to do is install Python and you&#8217;re done, but if you&#8217;re going to do Windows development, then you&#8217;ll need a few other packages to make it nicer.<span id="more-2052"></span></p>
<h2>Installing and Configuring Python</h2>
<p>Download <a href="http://www.python.org" target="_blank">Python</a> and run the installer. Make sure you got the version you want (i.e. Python 2.7 or 3.x). You&#8217;ll also want to make sure you get the bit type you want as there&#8217;s a 32-bit and a 64-bit version. <em>Note: The 32-bit Python will run just fine on a 64-bit system, but not vice versa!</em> Once you&#8217;ve got that installed, we&#8217;ll move on.</p>
<p>Now we’re going to make sure Python is set up right. Open a command window by going to Start –> Run and then typing “cmd” and pressing <strong>enter </strong>or <strong>return</strong>. Try typing “python” (without the quotes) in there and hitting your enter key. If you see the Python shell, then we’re halfway there. It should look something like this:</p>
<p><a href="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/python_shell.png"><img src="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/11/python_shell-300x148.png" alt="" title="python_shell" width="300" height="148" class="aligncenter size-medium wp-image-2069" /></a></p>
<p>If you don’t, then we need to modify some settings.</p>
<h3>Modifying Your Path</h3>
<p>On Windows, it can help a LOT to modify your Path settings by adding your Python path and the path to the Scripts folder to your System Path. Here&#8217;s one way that you can do it:</p>
<ol>
<li>Right-Click &#8220;My Computer&#8221; and choose <strong>Properties </strong>(Windows XP) or you may have to go digging in Control Panel on Windows 7 and do a &#8220;Show All Control Panel Items&#8221; from the path bar and look for <strong>System</strong>. You should see something like this:
<p><a href="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/08/system_properties_xp.png"><img src="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/08/system_properties_xp.png" alt="" title="system_properties_xp" width="419" height="479" class="aligncenter size-full wp-image-1891" /></a></p>
</li>
<li>Go to the <strong>Advanced</strong> tab and press the <strong>Environmental Variable</strong> button to see something like the following:
<p><a href="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/08/environment_vars_xp.png"><img src="http://www.blog.pythonlibrary.org/wp-content/uploads/2011/08/environment_vars_xp.png" alt="" title="environment_vars_xp" width="384" height="423" class="aligncenter size-full wp-image-1894" /></a>
</li>
<li>You will see two types of variables here. In the bottom section are <strong>System Variables</strong>. Scroll down to the one labeled <strong>Path</strong> and at the end of that, add the following two lines: ;C:\Python26;C:\Python26\Scripts  (adjust as necessary according to your version of Python and its location) Note that each entry is separated by a semi-colon, so make sure you do that too or this will not work!</li>
</ol>
<p>Now you should be able to run Python from the command line. Not only that, you&#8217;ll also be able to run the special scripts that were in Python&#8217;s Scripts folder. Why would you care? Well, if you install easy_install / SetupTools or pip, they will install stuff in the Scripts folder that you can run. Speaking of which, since you now have a brand new installation of Python, let&#8217;s take a moment to show you how to install a 3rd party package.</p>
<h2>How to Install a Package on Windows</h2>
<p>We will use pip as our example. It is used for the easy installation of Python packages from the Python Packages Index (PyPI, not to be confused with PyPy). Anyway, you&#8217;ll need to go <a href="http://pypi.python.org/pypi/pip" target="_blank">here</a> to download it. The pip package is in a tarred and gzipped download at the bottom of the page. You&#8217;ll probably need something like <a href="http://www.izarc.org/" target="_blank">IZArc</a> or <a href="http://www.filzip.com/" target="_blank">Filzip</a> to unzip it since Windows doesn&#8217;t unzip tar files natively.</p>
<p>Open up a command line window as you did before. Now you will need to use the &#8220;cd&#8221; command to change directories to the location that you unzipped the files to. This can take some practice. On my machine, I usually unzip to my desktop and just cd there and then into the unzipped package. Once you&#8217;re in the folder that has the <strong>setup.py</strong> file in it, all you need to do to install it is to type the following:</p>
<p><code><br />
python setup.py install<br />
</code></p>
<p>Most of the time, this works great and the package is installed correctly. Occasionally, you will run into certain packages that complain that they need a compiler. If you don&#8217;t have one installed (like Visual Studio or MingW), then you won&#8217;t be able to install the package this way. You will have to find a pre-packaged installer for it. On my machine, I usually have easy_install installed too. For some reason, the package is called <a href="http://pypi.python.org/pypi/setuptools" target="_blank">SetupTools </a>. Anyway, the main reason that you used to need easy_install was that it was the defacto standard for install Python Eggs, which you can read about <a href="http://mrtopf.de/blog/en/a-small-introduction-to-python-eggs/" target="_blank">here</a> or <a href="http://packages.python.org/distribute/easy_install.html" target="_blank">here</a>. Now you can use pip or <a href="http://pypi.python.org/pypi/distribute" target="_blank">distribute</a> to do the same thing. All three can also install packages that are in compressed archives. Normally, all you have to do to install a package with one of these utilities is something like this:</p>
<p><code><br />
easy_install PackageName<br />
pip install PackageName<br />
</code></p>
<p>Read their respective docs for more information though.</p>
<h2>Other Handy Packages for Windows Developers</h2>
<p>If you are a serious Windows developer who will need access to Windows APIs, then you will require the <a href="http://sourceforge.net/projects/pywin32/" target="_blank">PyWin32</a> package. You&#8217;ll want to become familiar with <a href="http://docs.python.org/library/ctypes.html" target="_blank">ctypes </a>too, but that&#8217;s been included with Python since version 2.5. PyWin32 is a lightweight wrapper around the Windows APIs. You can actually look on MSDN for the API documentation and almost directly translate it into Python. The ctypes package put on an even lower level and can be used to interact with DLLs directly, among many other things.</p>
<p>Another common need when programming on Windows is access to Window Management Instrumentation (WMI). Fortunately, Tim Golden has written a nice <a href="http://timgolden.me.uk/python/wmi/index.html" target="_blank">wmi module</a>. You can usually get the same information using PyWin32, but it&#8217;s more convoluted than just using WMI. Tim Golden has also written several other utilities:</p>
<ul>
<li><a href="http://timgolden.me.uk/python/winsys/index.html" target="_blank">WinSys</a> &#8211; Python tools for the Windows Administrator</li>
<li><a href="http://timgolden.me.uk/python/winshell.html" target="_blank">winshell</a> &#8211; a utility for getting Windows paths easily</li>
<li>An <a href="http://timgolden.me.uk/python/active_directory.html" target="_blank">Active Directory</a> wrapper</li>
</ul>
<p>You should also check out his awesome &#8220;<a href="http://timgolden.me.uk/python/win32_how_do_i.html" target="_blank">How Do I</a>&#8221; series of tutorials. </p>
<p>Finally, Python includes a module called <strong>_winreg</strong> that you can use to gain access to the Windows Registry. It&#8217;s a very powerful tool that&#8217;s very useful if you do a lot of administrative scripting on Windows.</p>
<h2>Other Python Installations for Windows</h2>
<p>The comments section started filling up with people mentioning the special Python installations you can get that actually include PyWin32 and other packages all wrapped up in one installer. That is also an option. Here are a few of those:</p>
<ul>
<li>PythonXY &#8211; This one includes a TON of other packages, including PyWin32, SciPy, wxPython, NumPy and dozens of others. It looks like a jack of all trades. I have not used this one, but it sounds interesting.</li>
<li>The <a href="http://www.enthought.com/products/getepd.php" target="_blank">Enthought Python Distribution</a> &#8211; That link is their paid version, but there&#8217;s also a <a href="http://enthought.com/products/epd_free.php" target="_blank">lightweight free version</a> available too.</li>
<li><a href="http://www.activestate.com/activepython/downloads" target="_blank">ActivePython </a>from ActiveState &#8211; this one has been around for a long time and includes the PyWin32 documentation and various other tools.</li>
</ul>
<h2>Wrapping Up</h2>
<p>You should now have all the tools you need to be an effective Windows developer with Python. If you need help, the PyWin32 and ctypes mailing lists are active and they have experts there that can answer just about anything you&#8217;d want to know about those packages.</p>
<h2>Further Reading</h2>
<ul>
<li>A Python Windows Registry <a href="http://www.blog.pythonlibrary.org/2010/03/20/pythons-_winreg-editing-the-windows-registry/" target="_blank">tutorial</a></li>
<li>Some other article on MvP about <a href="http://www.blog.pythonlibrary.org/tag/windows/" target="_blank">Windows and Python</a></li>
<li>Official <a href="http://docs.python.org/using/windows.html" target="_blank">Python documentation</a> on Windows</li>
<li>Another tutorial on <a href="http://www.imladris.com/Scripts/PythonForWindows.html" target="_blank">Python on Windows</a></li>
<li>PyWin32 <a href="http://docs.activestate.com/activepython/2.7/pywin32/PyWin32.HTML" target="_blank">documentation </a>from ActiveState</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2011/11/24/python-101-setting-up-python-on-windows/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Python: Changing Microsoft Office User Initials</title>
		<link>http://www.blog.pythonlibrary.org/2010/10/27/python-changing-microsoft-office-user-initials/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/10/27/python-changing-microsoft-office-user-initials/#comments</comments>
		<pubDate>Wed, 27 Oct 2010 23:37:36 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[System Administration]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Microsoft Office]]></category>
		<category><![CDATA[Registry]]></category>
		<category><![CDATA[System Admin]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1350</guid>
		<description><![CDATA[A couple of months ago at work, we received a report that a file was locked. The dialog that appeared showed the initials of a user who wasn&#8217;t even working for us any more. Thus we discovered an annoying bug that can crop up with Office. Basically, a user is asked by Word or Excel [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/10/27/python-changing-microsoft-office-user-initials/" data-url="http://bit.ly/sLXXCS" data-text="Python: Changing Microsoft Office User Initials" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/10/27/python-changing-microsoft-office-user-initials/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/10/27/python-changing-microsoft-office-user-initials/";
			reddit_title = "Python: Changing Microsoft Office User Initials";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/10/27/python-changing-microsoft-office-user-initials/"></g:plusone></div></div><p>A couple of months ago at work, we received a report that a file was locked. The dialog that appeared showed the initials of a user who wasn&#8217;t even working for us any more. Thus we discovered an annoying bug that can crop up with Office. Basically, a user is asked by Word or Excel to input their name and initials during the first run of that respective application and it will keep that data no matter who logs into the machine later on. This can lead to some serious confusion when we get error messages of this sort. Anyway, let&#8217;s take a quick look at how to get this done.<span id="more-1350"></span></p>
<p>We will be using Python&#8217;s <strong>_winreg</strong> module for this hack. You can see said hack below:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">_winreg</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
&nbsp;
key = CreateKey<span style="color: black;">&#40;</span>HKEY_CURRENT_USER,
                r<span style="color: #483d8b;">'Software<span style="color: #000099; font-weight: bold;">\M</span>icrosoft<span style="color: #000099; font-weight: bold;">\O</span>ffice<span style="color: #000099; font-weight: bold;">\1</span>1.0<span style="color: #000099; font-weight: bold;">\C</span>ommon<span style="color: #000099; font-weight: bold;">\U</span>serInfo'</span><span style="color: black;">&#41;</span>
res = QueryValueEx<span style="color: black;">&#40;</span>key, <span style="color: #483d8b;">&quot;UserInitials&quot;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #008000;">repr</span> <span style="color: black;">&#40;</span>res<span style="color: black;">&#41;</span>
&nbsp;
username = u<span style="color: #483d8b;">&quot;mldr<span style="color: #000099; font-weight: bold;">\0</span>&quot;</span>
SetValueEx<span style="color: black;">&#40;</span>key, <span style="color: #483d8b;">&quot;UserInitials&quot;</span>, <span style="color: #ff4500;">0</span>, REG_BINARY, username<span style="color: black;">&#41;</span>
CloseKey<span style="color: black;">&#40;</span>key<span style="color: black;">&#41;</span></pre>
<p>Here we use the <strong>CreateKey</strong> method just in case the key doesn&#8217;t already exist. If the key does exist, then CreateKey will just open it. The first half of the script was used for checking to see if the key had the correct value in it. The last three lines overwrite the value with my initials. I can&#8217;t remember why I had to make a unicode string, but the guys on PyWin32 told me that was the way to do it. I can tell you that I wasn&#8217;t ever able to get a plain string to work. Once the value is set, we clean up after ourselves by closing the key.</p>
<p>That&#8217;s it! Easy, eh? Have fun with Python!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/10/27/python-changing-microsoft-office-user-initials/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SqlAlchemy and Microsoft Access</title>
		<link>http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/#comments</comments>
		<pubDate>Sun, 10 Oct 2010 13:04:23 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[SqlAlchemy]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[databases]]></category>
		<category><![CDATA[microsoft access]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1291</guid>
		<description><![CDATA[Update (10/12/2010) &#8211; One of my alert readers told me that SqlAlchemy 0.6.x currently does NOT support the Access dialect. Read here for more info. A year or two ago, I was asked to transfer some data from some old Microsoft Access files to our Microsoft SQL Server. Since I enjoy using SqlAlchemy, I decided [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/" data-url="http://bit.ly/sjoTVA" data-text="SqlAlchemy and Microsoft Access" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/";
			reddit_title = "SqlAlchemy and Microsoft Access";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/"></g:plusone></div></div><p><strong>Update (10/12/2010) &#8211; One of my alert readers told me that SqlAlchemy 0.6.x currently does NOT support the Access dialect. Read <a href="http://www.sqlalchemy.org/docs/reference/dialects/index.html">here </a>for more info.</strong></p>
<p>A year or two ago, I was asked to transfer some data from some old Microsoft Access files to our Microsoft SQL Server. Since I enjoy using SqlAlchemy, I decided to see if it supported Access. The documentation at the time was pretty unhelpful in this regard, but it did seem to be possible and I found one thread about it on SqlAlchemy&#8217;s Google group.<span id="more-1291"></span></p>
<p>The code to connect to Microsoft Access is pretty simple. It goes something like this:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> sqlalchemy <span style="color: #ff7700;font-weight:bold;">import</span> create_engine
engine = create_engine<span style="color: black;">&#40;</span>r<span style="color: #483d8b;">'access:///C:/some/path/database.MDB'</span><span style="color: black;">&#41;</span></pre>
<p>See how easy that was? You just tell SqlAlchemy what kind of database to connect to, add three forward slashes and then the path to the file. Once that&#8217;s done, you can do pretty much anything with the Access file that you can do with a normal database:</p>
<pre class="python"><span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> TableName<span style="color: black;">&#40;</span>Base<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    MS Access database
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    __tablename__ = <span style="color: #483d8b;">&quot;ROW&quot;</span>
    __table_args__ = <span style="color: black;">&#40;</span><span style="color: black;">&#123;</span><span style="color: #483d8b;">&quot;autoload&quot;</span>:<span style="color: #008000;">True</span><span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>  <span style="color: #808080; font-style: italic;"># load the database</span>
    FILENUM = Column<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;FILE #&quot;</span>, Integer, key=<span style="color: #483d8b;">&quot;FILENUM&quot;</span><span style="color: black;">&#41;</span></pre>
<p>In the code above, I use SqlAlchemy&#8217;s declarative syntax to autoload the database&#8217;s structure. I can&#8217;t recall is this database had its primary key set, but I&#8217;m guessing it didn&#8217;t since I had to add that last line.</p>
<p>Anyway, once you have your connection, you can just run queries as you normally would. In my case, I ended up creating a model file to hold all the table definitions for the Access file and the SQL Server database, then I did a SELECT * on the Access file, looped over the result and inserted each row into the SQL Server one. The only thing you have to watch out for is that Access is a lot more forgiving of NULLS than SQL Server is, so I had to write some special handling around that atrocity.</p>
<p>Well, that&#8217;s really all there is to it. You can check out my other SqlAlchemy tutorials for more general information about using SqlAlchemy to interact with your database.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/10/10/sqlalchemy-and-microsoft-access/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Getting Remote Drive Space on Windows</title>
		<link>http://www.blog.pythonlibrary.org/2010/09/09/getting-remote-drive-space-on-windows/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/09/09/getting-remote-drive-space-on-windows/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 22:50:00 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[System Administration]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[System Admin]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1196</guid>
		<description><![CDATA[After about a year or so at my current job, as we were still working on upgrading the last few Windows 98 machines to Windows XP, we had a need to check which machines on our network were getting low on disk space. The issue was cropping up because we had Windows XP loaded on [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/09/09/getting-remote-drive-space-on-windows/" data-url="http://bit.ly/vX4W5I" data-text="Getting Remote Drive Space on Windows" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/09/09/getting-remote-drive-space-on-windows/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/09/09/getting-remote-drive-space-on-windows/";
			reddit_title = "Getting Remote Drive Space on Windows";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/09/09/getting-remote-drive-space-on-windows/"></g:plusone></div></div><p>After about a year or so at my current job, as we were still working on upgrading the last few Windows 98 machines to Windows XP, we had a need to check which machines on our network were getting low on disk space. The issue was cropping up because we had Windows XP loaded on several machines that had 10 GB hard drives and a few with 20 GB and one or two with just 4 GB. Anyway, after some digging online, I discovered that the PyWin32 package could accomplish what I needed.<span id="more-1196"></span></p>
<p>Here is the code that I used:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> win32com.<span style="color: black;">client</span> as com
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> TotalSize<span style="color: black;">&#40;</span>drive<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot; Return the TotalSize of a shared drive [GB]&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        fso = com.<span style="color: black;">Dispatch</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Scripting.FileSystemObject&quot;</span><span style="color: black;">&#41;</span>
        drv = fso.<span style="color: black;">GetDrive</span><span style="color: black;">&#40;</span>drive<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> drv.<span style="color: black;">TotalSize</span>/<span style="color: #ff4500;">2</span><span style="color: #66cc66;">**</span><span style="color: #ff4500;">30</span>
    <span style="color: #ff7700;font-weight:bold;">except</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #ff4500;">0</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> FreeSpace<span style="color: black;">&#40;</span>drive<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot; Return the FreeSpace of a shared drive [GB]&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        fso = com.<span style="color: black;">Dispatch</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Scripting.FileSystemObject&quot;</span><span style="color: black;">&#41;</span>
        drv = fso.<span style="color: black;">GetDrive</span><span style="color: black;">&#40;</span>drive<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> drv.<span style="color: black;">FreeSpace</span>/<span style="color: #ff4500;">2</span><span style="color: #66cc66;">**</span><span style="color: #ff4500;">30</span>
    <span style="color: #ff7700;font-weight:bold;">except</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #ff4500;">0</span>
&nbsp;
workstations = <span style="color: black;">&#91;</span><span style="color: #483d8b;">'computeNameOne'</span><span style="color: black;">&#93;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Hard drive sizes:'</span>
<span style="color: #ff7700;font-weight:bold;">for</span> compName <span style="color: #ff7700;font-weight:bold;">in</span> workstations:
    drive = <span style="color: #483d8b;">'<span style="color: #000099; font-weight: bold;">\\</span><span style="color: #000099; font-weight: bold;">\\</span>'</span> + compName + <span style="color: #483d8b;">'<span style="color: #000099; font-weight: bold;">\\</span>c$'</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'*************************************************<span style="color: #000099; font-weight: bold;">\n</span>'</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> compName
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'TotalSize of %s = %f GB'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>drive, TotalSize<span style="color: black;">&#40;</span>drive<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'FreeSpace on %s = %f GB'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>drive, FreeSpace<span style="color: black;">&#40;</span>drive<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'*************************************************<span style="color: #000099; font-weight: bold;">\n</span>'</span></pre>
<p>Note at the bottom that I used a list. Normally, I would list the computer names of every computer that I wanted to check. Then I would iterate over those names and put together the right path that I needed from a machine with full domain admin rights.</p>
<p>To get this to work, we needed to import win32com.client and call the following: <strong>com.Dispatch(&#8220;Scripting.FileSystemObject&#8221;)</strong>. This would get us a COM object that we could query to get a disk object. Once we had that, we can ask the disk how much total space it had and how much free space. Looking at this code today, I would combine the two functions into one and return a tuple. As you can see, I do a little bit of math on the result to get it to return the size in gigabytes. </p>
<p>That&#8217;s all there is to it. Simple stuff. I suspect that I didn&#8217;t write this code completely since the variable names suck. It is probably from an ActiveState recipe or a forum and I forgot to attribute it. If you recognize the code, let me know in the comments!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/09/09/getting-remote-drive-space-on-windows/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A PyInstaller Tutorial &#8211; Build a Binary Series!</title>
		<link>http://www.blog.pythonlibrary.org/2010/08/10/a-pyinstaller-tutorial-build-a-binary-series/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/08/10/a-pyinstaller-tutorial-build-a-binary-series/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 01:36:13 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Packaging]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[binaries]]></category>
		<category><![CDATA[Distribution]]></category>
		<category><![CDATA[PyInstaller]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1102</guid>
		<description><![CDATA[In our previous article on building binaries, we learned a little about py2exe. This time around, we will be focusing our collective attention on the ins and outs of PyInstaller. We&#8217;ll use the same lame wxPython script from the last article for one of our examples, but we&#8217;ll also try a normal console script to [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/08/10/a-pyinstaller-tutorial-build-a-binary-series/" data-url="http://bit.ly/sniyEP" data-text="A PyInstaller Tutorial &#8211; Build a Binary Series!" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/08/10/a-pyinstaller-tutorial-build-a-binary-series/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>In our previous article on building binaries, we learned a little about py2exe. This time around, we will be focusing our collective attention on the ins and outs of PyInstaller. We&#8217;ll use the same lame wxPython script from the last <a href="http://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/">article </a>for one of our examples, but we&#8217;ll also try a normal console script to see what the differences are, if any. In case you didn&#8217;t know, PyInstaller works on Linux, Windows and Mac (experimental) and works with Python 1.5-2.6 (except on Windows, where there&#8217;s a caveat for 2.6 &#8211; see below). PyInstaller supports code-signing (Windows), eggs, hidden imports, single executable, single directory, and lots more!<span id="more-1102"></span></p>
<h2>Getting Started with PyInstaller</h2>
<p><strong>Note on Python 2.6 on Windows: </strong>If you read the PyInstaller <a href="http://www.pyinstaller.org/wiki/Python26Win">website </a>closely, you will see a warning about Python 2.6+ not being fully supported. The note says that you will currently need to have the Microsoft CRT installed for your executable to work. What this is probably referring to is the side-by-side assemblies / manifest issues that were introduced with Python 2.6 vis-a-vis Microsoft Visual Studio 2008. We already mentioned this problem in the first article. If you don&#8217;t know anything about it, please check out the py2exe website, the wxPython wiki or Google for the issue.</p>
<p>Anyway, let&#8217;s get on with the show. After you download PyInstaller, you just unzip the archive somewhere convenient. The follow these three simple steps:</p>
<ol>
<li>Run <strong>Configure.py</strong> to save some basic configuration data to a &#8220;.dat&#8221; file. This saves some time since PyInstaller won&#8217;t have to recalculate the configuration on the fly.</li>
<li>Run the following command on the command line:  <em>python Makespec.py [opts] <scriptname></em> where scriptname is the name of the main Python file you use to run your program.</li>
<li>Finally, run the following command via the command line:  <em>python Build.py specfile</em> to build your executable.</li>
</ol>
<p>Let&#8217;s run through this with a real script now. We&#8217;ll start with a simple console script that creates a faux configuration file. Here&#8217;s the code:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> configobj
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> createConfig<span style="color: black;">&#40;</span>configFile<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Create the configuration file
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    config = configobj.<span style="color: black;">ConfigObj</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    inifile = configFile
    config.<span style="color: black;">filename</span> = inifile
    config<span style="color: black;">&#91;</span><span style="color: #483d8b;">'server'</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">&quot;http://www.google.com&quot;</span>
    config<span style="color: black;">&#91;</span><span style="color: #483d8b;">'username'</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">&quot;mike&quot;</span>
    config<span style="color: black;">&#91;</span><span style="color: #483d8b;">'password'</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">&quot;dingbat&quot;</span>
    config<span style="color: black;">&#91;</span><span style="color: #483d8b;">'update interval'</span><span style="color: black;">&#93;</span> = <span style="color: #ff4500;">2</span>
    config.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> getConfig<span style="color: black;">&#40;</span>configFile<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Open the config file and return a configobj
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> configobj.<span style="color: black;">ConfigObj</span><span style="color: black;">&#40;</span>configFile<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> createConfig2<span style="color: black;">&#40;</span>path<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Create a config file
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    config = configobj.<span style="color: black;">ConfigObj</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    config.<span style="color: black;">filename</span> = path
    config<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;Sony&quot;</span><span style="color: black;">&#93;</span> = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
    config<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;Sony&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;product&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">&quot;Sony PS3&quot;</span>
    config<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;Sony&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;accessories&quot;</span><span style="color: black;">&#93;</span> = <span style="color: black;">&#91;</span><span style="color: #483d8b;">'controller'</span>, <span style="color: #483d8b;">'eye'</span>, <span style="color: #483d8b;">'memory stick'</span><span style="color: black;">&#93;</span>
    config<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;Sony&quot;</span><span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;retail price&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #483d8b;">&quot;$400&quot;</span>
    config.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    createConfig2<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sampleConfig.ini&quot;</span><span style="color: black;">&#41;</span></pre>
<p>Now let&#8217;s make a spec file:</p>
<p><code><br />
c:\Python25\python c:\Users\Mike\Desktop\pyinstaller-1.4\Makespec.py config_1.py<br />
</code></p>
<p>On my test machine, I have 3 different Python versions installed, so I had to specify the Python 2.5 path explicitly (or set Python 2.5 as the default). Anyway, this should create a file similar to the following (which was named &#8220;config_1.spec&#8221;):</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># -*- mode: python -*-</span>
a = Analysis<span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>HOMEPATH,<span style="color: #483d8b;">'support<span style="color: #000099; font-weight: bold;">\\</span>_mountzlib.py'</span><span style="color: black;">&#41;</span>, <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>HOMEPATH,<span style="color: #483d8b;">'support<span style="color: #000099; font-weight: bold;">\\</span>useUnicode.py'</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'config_1.py'</span><span style="color: black;">&#93;</span>,
             pathex=<span style="color: black;">&#91;</span><span style="color: #483d8b;">'C:<span style="color: #000099; font-weight: bold;">\\</span>Users<span style="color: #000099; font-weight: bold;">\\</span>Mike<span style="color: #000099; font-weight: bold;">\\</span>Desktop<span style="color: #000099; font-weight: bold;">\\</span>py2exe_ex'</span>, r<span style="color: #483d8b;">'C:<span style="color: #000099; font-weight: bold;">\P</span>ython26<span style="color: #000099; font-weight: bold;">\L</span>ib<span style="color: #000099; font-weight: bold;">\s</span>ite-packages'</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
pyz = PYZ<span style="color: black;">&#40;</span>a.<span style="color: black;">pure</span><span style="color: black;">&#41;</span>
exe = EXE<span style="color: black;">&#40;</span>pyz,
          a.<span style="color: black;">scripts</span>,
          exclude_binaries=<span style="color: #ff4500;">1</span>,
          name=<span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'build<span style="color: #000099; font-weight: bold;">\\</span>pyi.win32<span style="color: #000099; font-weight: bold;">\\</span>config_1'</span>, <span style="color: #483d8b;">'config_1.exe'</span><span style="color: black;">&#41;</span>,
          debug=<span style="color: #008000;">False</span>,
          strip=<span style="color: #008000;">False</span>,
          upx=<span style="color: #008000;">True</span>,
          console=<span style="color: #008000;">True</span> <span style="color: black;">&#41;</span>
coll = COLLECT<span style="color: black;">&#40;</span> exe,
               a.<span style="color: black;">binaries</span>,
               a.<span style="color: black;">zipfiles</span>,
               a.<span style="color: black;">datas</span>,
               strip=<span style="color: #008000;">False</span>,
               upx=<span style="color: #008000;">True</span>,
               name=<span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'pyInstDist2'</span>, <span style="color: #483d8b;">'config_1'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre>
<p>For the Python script we&#8217;re using, we need to add an explicit path to the location of <em>configobj.py</em> in the <em>Analysis </em>section of the spec file in the <em>pathex</em> parameter. If you do not do this, when you run the resulting executable, it will open and close a console window really fast and you won&#8217;t be able to tell what it says unless you run the exe from the command line. I did the latter to find out what was wrong and discovered it could not find the configobj module. You can also specify the output path for your exe in the COLLECT function&#8217;s name parameter. In this case, we put PyInstaller&#8217;s output in the &#8220;config_1&#8243; subfolder of &#8220;pyInstDist2&#8243;, which should be a folder alongside your original script. There are a ton of options when configuring your spec file, which you can read about <a href="http://www.pyinstaller.org/export/latest/tags/1.4/doc/Manual.html?format=raw#configuring-your-pyinstaller-setup">here</a>.</p>
<p>To build the executable based on the spec file, do the following on the command line:</p>
<p><code><br />
c:\Python25\python c:\Users\Mike\Desktop\pyinstaller-1.4\Build.py config_1.spec<br />
</code></p>
<p>On my machine, I ended up with a folder that had 25 files in it that totaled 6.7 MB. You should be able to reduce the size using the Analysis section&#8217;s <em>excludes</em> parameter and/or compression.</p>
<h2>PyInstaller and wxPython</h2>
<p>Now let&#8217;s try creating a binary from a simple wxPython script. Here&#8217;s the Python script:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> wx
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> DemoPanel<span style="color: black;">&#40;</span>wx.<span style="color: black;">Panel</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, parent<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        wx.<span style="color: black;">Panel</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, parent<span style="color: black;">&#41;</span>
&nbsp;
        labels = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;Name&quot;</span>, <span style="color: #483d8b;">&quot;Address&quot;</span>, <span style="color: #483d8b;">&quot;City&quot;</span>, <span style="color: #483d8b;">&quot;State&quot;</span>, <span style="color: #483d8b;">&quot;Zip&quot;</span>,
                  <span style="color: #483d8b;">&quot;Phone&quot;</span>, <span style="color: #483d8b;">&quot;Email&quot;</span>, <span style="color: #483d8b;">&quot;Notes&quot;</span><span style="color: black;">&#93;</span>
&nbsp;
        mainSizer = wx.<span style="color: black;">BoxSizer</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">VERTICAL</span><span style="color: black;">&#41;</span>
        lbl = wx.<span style="color: black;">StaticText</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=<span style="color: #483d8b;">&quot;Please enter your information here:&quot;</span><span style="color: black;">&#41;</span>
        lbl.<span style="color: black;">SetFont</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">Font</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">12</span>, wx.<span style="color: black;">SWISS</span>, wx.<span style="color: black;">NORMAL</span>, wx.<span style="color: black;">BOLD</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        mainSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>lbl, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> lbl <span style="color: #ff7700;font-weight:bold;">in</span> labels:
            sizer = <span style="color: #008000;">self</span>.<span style="color: black;">buildControls</span><span style="color: black;">&#40;</span>lbl<span style="color: black;">&#41;</span>
            mainSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>sizer, <span style="color: #ff4500;">1</span>, wx.<span style="color: black;">EXPAND</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">SetSizer</span><span style="color: black;">&#40;</span>mainSizer<span style="color: black;">&#41;</span>
        mainSizer.<span style="color: black;">Layout</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> buildControls<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        sizer = wx.<span style="color: black;">BoxSizer</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">HORIZONTAL</span><span style="color: black;">&#41;</span>
        size = <span style="color: black;">&#40;</span><span style="color: #ff4500;">80</span>,<span style="color: #ff4500;">40</span><span style="color: black;">&#41;</span>
        font = wx.<span style="color: black;">Font</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">12</span>, wx.<span style="color: black;">SWISS</span>, wx.<span style="color: black;">NORMAL</span>, wx.<span style="color: black;">BOLD</span><span style="color: black;">&#41;</span>
&nbsp;
        lbl = wx.<span style="color: black;">StaticText</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=label, size=size<span style="color: black;">&#41;</span>
        lbl.<span style="color: black;">SetFont</span><span style="color: black;">&#40;</span>font<span style="color: black;">&#41;</span>
        sizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>lbl, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>|wx.<span style="color: black;">CENTER</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> label <span style="color: #66cc66;">!</span>= <span style="color: #483d8b;">&quot;Notes&quot;</span>:
            txt = wx.<span style="color: black;">TextCtrl</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name=label<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            txt = wx.<span style="color: black;">TextCtrl</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, style=wx.<span style="color: black;">TE_MULTILINE</span>, name=label<span style="color: black;">&#41;</span>
        sizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>txt, <span style="color: #ff4500;">1</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> sizer
&nbsp;
&nbsp;
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> DemoFrame<span style="color: black;">&#40;</span>wx.<span style="color: black;">Frame</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Frame that holds all other widgets
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        wx.<span style="color: black;">Frame</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #008000;">None</span>, wx.<span style="color: black;">ID_ANY</span>,
                          <span style="color: #483d8b;">&quot;PyInstaller Tutorial&quot;</span>,
                          size=<span style="color: black;">&#40;</span><span style="color: #ff4500;">600</span>,<span style="color: #ff4500;">400</span><span style="color: black;">&#41;</span>
                          <span style="color: black;">&#41;</span>
        panel = DemoPanel<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">Show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    app = wx.<span style="color: black;">App</span><span style="color: black;">&#40;</span><span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
    frame = DemoFrame<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    app.<span style="color: black;">MainLoop</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>Since this is a GUI, we&#8217;ll create our spec file slightly differently:</p>
<p><code><br />
c:\Python25\python c:\Users\Mike\Desktop\pyinstaller-1.4\Makespec.py -F -w sampleApp.py<br />
</code></p>
<p>Note the -F and -w parameters. The -F command tells PyInstaller to create just one executable whereas the -w tells PyInstaller to hide the console window. Here&#8217;s the resulting spec file:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># -*- mode: python -*-</span>
a = Analysis<span style="color: black;">&#40;</span><span style="color: black;">&#91;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>HOMEPATH,<span style="color: #483d8b;">'support<span style="color: #000099; font-weight: bold;">\\</span>_mountzlib.py'</span><span style="color: black;">&#41;</span>, <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>HOMEPATH,<span style="color: #483d8b;">'support<span style="color: #000099; font-weight: bold;">\\</span>useUnicode.py'</span><span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'sampleApp.py'</span><span style="color: black;">&#93;</span>,
             pathex=<span style="color: black;">&#91;</span><span style="color: #483d8b;">'C:<span style="color: #000099; font-weight: bold;">\\</span>Users<span style="color: #000099; font-weight: bold;">\\</span>Mike<span style="color: #000099; font-weight: bold;">\\</span>Desktop<span style="color: #000099; font-weight: bold;">\\</span>py2exe_ex'</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
pyz = PYZ<span style="color: black;">&#40;</span>a.<span style="color: black;">pure</span><span style="color: black;">&#41;</span>
exe = EXE<span style="color: black;">&#40;</span> pyz,
          a.<span style="color: black;">scripts</span>,
          a.<span style="color: black;">binaries</span>,
          a.<span style="color: black;">zipfiles</span>,
          a.<span style="color: black;">datas</span>,
          name=<span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'pyInstDist'</span>, <span style="color: #483d8b;">'sampleApp.exe'</span><span style="color: black;">&#41;</span>,
          debug=<span style="color: #008000;">False</span>,
          strip=<span style="color: #008000;">False</span>,
          upx=<span style="color: #008000;">True</span>,
          console=<span style="color: #008000;">False</span> <span style="color: black;">&#41;</span></pre>
<p>Note that the last line has the &#8220;console&#8221; parameter set to &#8220;False&#8221;. If you build this like you did with the console script you should end up with one file in the &#8220;pyInstDist&#8221; folder that is approximately 7.1 MB in size. </p>
<h2>Wrapping Up</h2>
<p>This ends our quick tour of PyInstaller. I hope you found this helpful in your Python binary-making endeavors. There is much more information on the PyInstaller website and it&#8217;s pretty well documented, although the website is pretty plain. Be sure to give it a try and see just how much easy PyInstaller is to use!</p>
<p><em>Note: I tested all this using PyInstaller 1.4 and Python 2.5 on Windows 7 Home Premium (32-bit).</em></p>
<h2>Further Reading</h2>
<ul>
<li>PyInstaller Official <a href="http://www.pyinstaller.org">Website</a>, <a href="http://www.pyinstaller.org/export/latest/tags/1.4/doc/Manual.html?format=raw">Manual</a>, <a href="http://groups-beta.google.com/group/PyInstaller?pli=1">Mailing List</a></li>
<li>First <a href="http://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/">article </a>in the &#8220;Build a Binary Series&#8221;</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/08/10/a-pyinstaller-tutorial-build-a-binary-series/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PyWin32: Getting Windows Event Logs</title>
		<link>http://www.blog.pythonlibrary.org/2010/07/27/pywin32-getting-windows-event-logs/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/07/27/pywin32-getting-windows-event-logs/#comments</comments>
		<pubDate>Tue, 27 Jul 2010 12:14:28 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[System Administration]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[PyWin32]]></category>
		<category><![CDATA[System Admin]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1071</guid>
		<description><![CDATA[The other day, there was a post on one of the mailing lists that I follow about accessing the Windows Event Logs. I thought that was an interesting topic, so I went looking for examples and found a pretty nice example on ActiveState. In this article, you&#8217;ll find out what I discovered. It&#8217;s probably easiest [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/07/27/pywin32-getting-windows-event-logs/" data-url="http://bit.ly/tv7oEF" data-text="PyWin32: Getting Windows Event Logs" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/07/27/pywin32-getting-windows-event-logs/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/07/27/pywin32-getting-windows-event-logs/";
			reddit_title = "PyWin32: Getting Windows Event Logs";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/07/27/pywin32-getting-windows-event-logs/"></g:plusone></div></div><p>The  other day, there was a post on one of the mailing lists that I follow about accessing the Windows Event Logs. I thought that was an interesting topic, so I went looking for examples and found a pretty nice example on <a href="http://docs.activestate.com/activepython/2.5/pywin32/Windows_NT_Eventlog.html">ActiveState</a>. In this article, you&#8217;ll find out what I discovered.<span id="more-1071"></span></p>
<p>It&#8217;s probably easiest to just jump right into the code. Note that the only thing other than Python that you will need is the PyWin32 package. Once you&#8217;ve got that, then you can follow along:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">codecs</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">traceback</span>
<span style="color: #ff7700;font-weight:bold;">import</span> win32con
<span style="color: #ff7700;font-weight:bold;">import</span> win32evtlog
<span style="color: #ff7700;font-weight:bold;">import</span> win32evtlogutil
<span style="color: #ff7700;font-weight:bold;">import</span> winerror
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> getAllEvents<span style="color: black;">&#40;</span>server, logtypes, basePath<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> server:
        serverName = <span style="color: #483d8b;">&quot;localhost&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        serverName = server
    <span style="color: #ff7700;font-weight:bold;">for</span> logtype <span style="color: #ff7700;font-weight:bold;">in</span> logtypes:
        path = <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>basePath, <span style="color: #483d8b;">&quot;%s_%s_log.log&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>serverName, logtype<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        getEventLogs<span style="color: black;">&#40;</span>server, logtype, path<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> getEventLogs<span style="color: black;">&#40;</span>server, logtype, logPath<span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
    Get the event logs from the specified machine according to the
    logtype (Example: Application) and save it to the appropriately
    named log file
    &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Logging %s events&quot;</span> <span style="color: #66cc66;">%</span> logtype
    log = <span style="color: #dc143c;">codecs</span>.<span style="color: #008000;">open</span><span style="color: black;">&#40;</span>logPath, encoding=<span style="color: #483d8b;">'utf-8'</span>, mode=<span style="color: #483d8b;">'w'</span><span style="color: black;">&#41;</span>
    line_break = <span style="color: #483d8b;">'-'</span> <span style="color: #66cc66;">*</span> <span style="color: #ff4500;">80</span>
&nbsp;
    log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>%s Log of %s Events<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>server, logtype<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Created: %s<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: #dc143c;">time</span>.<span style="color: black;">ctime</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> + line_break + <span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: black;">&#41;</span>
    hand = win32evtlog.<span style="color: black;">OpenEventLog</span><span style="color: black;">&#40;</span>server,logtype<span style="color: black;">&#41;</span>
    total = win32evtlog.<span style="color: black;">GetNumberOfEventLogRecords</span><span style="color: black;">&#40;</span>hand<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Total events in %s = %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>logtype, total<span style="color: black;">&#41;</span>
    flags = win32evtlog.<span style="color: black;">EVENTLOG_BACKWARDS_READ</span>|win32evtlog.<span style="color: black;">EVENTLOG_SEQUENTIAL_READ</span>
    events = win32evtlog.<span style="color: black;">ReadEventLog</span><span style="color: black;">&#40;</span>hand,flags,<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
    evt_dict=<span style="color: black;">&#123;</span>win32con.<span style="color: black;">EVENTLOG_AUDIT_FAILURE</span>:<span style="color: #483d8b;">'EVENTLOG_AUDIT_FAILURE'</span>,
              win32con.<span style="color: black;">EVENTLOG_AUDIT_SUCCESS</span>:<span style="color: #483d8b;">'EVENTLOG_AUDIT_SUCCESS'</span>,
              win32con.<span style="color: black;">EVENTLOG_INFORMATION_TYPE</span>:<span style="color: #483d8b;">'EVENTLOG_INFORMATION_TYPE'</span>,
              win32con.<span style="color: black;">EVENTLOG_WARNING_TYPE</span>:<span style="color: #483d8b;">'EVENTLOG_WARNING_TYPE'</span>,
              win32con.<span style="color: black;">EVENTLOG_ERROR_TYPE</span>:<span style="color: #483d8b;">'EVENTLOG_ERROR_TYPE'</span><span style="color: black;">&#125;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        events=<span style="color: #ff4500;">1</span>
        <span style="color: #ff7700;font-weight:bold;">while</span> events:
            events=win32evtlog.<span style="color: black;">ReadEventLog</span><span style="color: black;">&#40;</span>hand,flags,<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
&nbsp;
            <span style="color: #ff7700;font-weight:bold;">for</span> ev_obj <span style="color: #ff7700;font-weight:bold;">in</span> events:
                the_time = ev_obj.<span style="color: black;">TimeGenerated</span>.<span style="color: black;">Format</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #808080; font-style: italic;">#'12/23/99 15:54:09'</span>
                evt_id = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>winerror.<span style="color: black;">HRESULT_CODE</span><span style="color: black;">&#40;</span>ev_obj.<span style="color: black;">EventID</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
                computer = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>ev_obj.<span style="color: black;">ComputerName</span><span style="color: black;">&#41;</span>
                cat = ev_obj.<span style="color: black;">EventCategory</span>
        <span style="color: #808080; font-style: italic;">##        seconds=date2sec(the_time)</span>
                record = ev_obj.<span style="color: black;">RecordNumber</span>
                msg = win32evtlogutil.<span style="color: black;">SafeFormatMessage</span><span style="color: black;">&#40;</span>ev_obj, logtype<span style="color: black;">&#41;</span>
&nbsp;
                source = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>ev_obj.<span style="color: black;">SourceName</span><span style="color: black;">&#41;</span>
                <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> ev_obj.<span style="color: black;">EventType</span> <span style="color: #ff7700;font-weight:bold;">in</span> evt_dict.<span style="color: black;">keys</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
                    evt_type = <span style="color: #483d8b;">&quot;unknown&quot;</span>
                <span style="color: #ff7700;font-weight:bold;">else</span>:
                    evt_type = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>evt_dict<span style="color: black;">&#91;</span>ev_obj.<span style="color: black;">EventType</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
                log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Event Date/Time: %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #66cc66;">%</span> the_time<span style="color: black;">&#41;</span>
                log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Event ID / Type: %s / %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>evt_id, evt_type<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
                log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Record #%s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #66cc66;">%</span> record<span style="color: black;">&#41;</span>
                log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Source: %s<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #66cc66;">%</span> source<span style="color: black;">&#41;</span>
                log.<span style="color: black;">write</span><span style="color: black;">&#40;</span>msg<span style="color: black;">&#41;</span>
                log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: black;">&#41;</span>
                log.<span style="color: black;">write</span><span style="color: black;">&#40;</span>line_break<span style="color: black;">&#41;</span>
                log.<span style="color: black;">write</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">except</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #dc143c;">traceback</span>.<span style="color: black;">print_exc</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">exc_info</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Log creation finished. Location of log is %s&quot;</span> <span style="color: #66cc66;">%</span> logPath
&nbsp;
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    server = <span style="color: #008000;">None</span>  <span style="color: #808080; font-style: italic;"># None = local machine</span>
    logTypes = <span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;System&quot;</span>, <span style="color: #483d8b;">&quot;Application&quot;</span>, <span style="color: #483d8b;">&quot;Security&quot;</span><span style="color: black;">&#93;</span>
    getAllEvents<span style="color: black;">&#40;</span>server, logTypes, <span style="color: #483d8b;">&quot;C:<span style="color: #000099; font-weight: bold;">\d</span>ownloads&quot;</span><span style="color: black;">&#41;</span></pre>
<p>There are a couple potential caveats to this type of scripting. I tested this code as an Administrator on my PCs and as a Domain Administrator at work. I did not test it as any other type of user. So if you have problems getting this code to run, check your permissions. I tested this from Windows XP  and Windows 7. The UAC doesn&#8217;t appear to block this activity on Windows 7, so that made it just as easy to use as XP did. However, Windows 7&#8242;s events had some unicode in the message portion of the code whereas XP did not. Watch out for that and handle it accordingly.</p>
<p>Anyway, let&#8217;s unpack this script and see how it works. First we have a number of imports. We use the <em>codecs</em> modules to encode the log file in utf-8 just in case there&#8217;s some sneaky unicode in the message. We use PyWin32&#8242;s <em>win32evtlog</em> module to open the event log and pull information out of it. According to the article I mentioned at the beginning, to get all the events from the log, you need to call <em>win32evtlog.ReadEventLog</em> repeatedly until it stops returning events. Thus, we use <em>while </em>loop. Inside the while loop, we use a <em>for</em> loop to iterate over the events and extract the event ID, record number, event message, event source and a few other tidbits. We log it and then we exit the <em>for</em> loop and the <em>while</em> loop calls the <em>win32evtlog.ReadEventLog</em> again.</p>
<p>We use the <em>traceback</em> module to print out any errors that occur during the script&#8217;s run. And that&#8217;s all there is to it!</p>
<h2>Wrapping Up</h2>
<p>As you can see, using the PyWin32 package is easy. If you get stuck, it has some great documentation. If that documentation isn&#8217;t good enough though, you can fall back on MSDN instead. PyWin32 is a light wrapper around Windows&#8217; API, so using MSDN&#8217;s instructions is fairly simple. Anyway, I hope you learned a lot and will find it helpful.</p>
<h2>Further Reading</h2>
<ul>
<li><a href="http://docs.python.org/howto/unicode.html">Python and Unicode</a></li>
<li><a href="http://sourceforge.net/projects/pywin32/">PyWin32</a></li>
<li>PyWin32 <a href="http://docs.activestate.com/activepython/2.5/pywin32/PyWin32.HTML">Documentation </a>from ActiveState</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/07/27/pywin32-getting-windows-event-logs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python and Microsoft Office &#8211; Using PyWin32</title>
		<link>http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/#comments</comments>
		<pubDate>Fri, 16 Jul 2010 14:18:55 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[PyWin32]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Excel]]></category>
		<category><![CDATA[Word]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=1040</guid>
		<description><![CDATA[Most typical users have used Microsoft Office. While Office may be the bane of tech support, we still have to deal with it. Python can be used to script (AKA automate) Office and make it easier for us or our users to use. It may not be as easy as recording a macro, but it&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/" data-url="http://bit.ly/slX7j5" data-text="Python and Microsoft Office &#8211; Using PyWin32" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/";
			reddit_title = "Python and Microsoft Office &#8211; Using PyWin32";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/"></g:plusone></div></div><p>Most typical users have used Microsoft Office. While Office may be the bane of tech support, we still have to deal with it. Python can be used to script (AKA automate) Office and make it easier for us or our users to use. It may not be as easy as recording a macro, but it&#8217;s close. For this article, you will learn how to use the PyWin32 module to access some of the Office programs and manipulate them with Python. Some forums say that you need to run PythonWin&#8217;s makepy utility on Microsoft Word (and Excel) before you can access Office applications. I don&#8217;t think I needed to do that to make it work though (at least, not with the 2007 version). However, PythonWin comes with the PyWin32, so if you do run into trouble, you can try it.<span id="more-1040"></span></p>
<h2>Python and Microsoft Excel</h2>
<p>If you&#8217;ve looked for examples of using Python and Office, you&#8217;ll usually find that the most often hacked component is Excel. In fact, there are several non-PyWin32 modules specifically created to read and write Excel files. They are called xlrd and xlwt, respectively. But that&#8217;s a topic for another article. Here we&#8217;ll see how to mess with Excel using the PyWin32 interface. Note that the following scripts only work on Windows. One advantage of xlrd and xlwt is that you can use them on any platform.</p>
<p>Let&#8217;s take a look at a simple example, shall we?</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
<span style="color: #ff7700;font-weight:bold;">import</span> win32com.<span style="color: black;">client</span> as win32
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">def</span> excel<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
    xl = win32.<span style="color: black;">gencache</span>.<span style="color: black;">EnsureDispatch</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Excel.Application'</span><span style="color: black;">&#41;</span>
    ss = xl.<span style="color: black;">Workbooks</span>.<span style="color: black;">Add</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    sh = ss.<span style="color: black;">ActiveSheet</span>
&nbsp;
    xl.<span style="color: black;">Visible</span> = <span style="color: #008000;">True</span>
    <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
&nbsp;
    sh.<span style="color: black;">Cells</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>,<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>.<span style="color: black;">Value</span> = <span style="color: #483d8b;">'Hacking Excel with Python Demo'</span>
&nbsp;
    <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">2</span>,<span style="color: #ff4500;">8</span><span style="color: black;">&#41;</span>:
        sh.<span style="color: black;">Cells</span><span style="color: black;">&#40;</span>i,<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>.<span style="color: black;">Value</span> = <span style="color: #483d8b;">'Line %i'</span> <span style="color: #66cc66;">%</span> i
        <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
&nbsp;
    ss.<span style="color: black;">Close</span><span style="color: black;">&#40;</span><span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
    xl.<span style="color: black;">Application</span>.<span style="color: black;">Quit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    excel<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>The example above is similar to what you will normally find on the web. It is actually based on an example I saw in Wesley Chun&#8217;s excellent book, <em>Core Python Programming</em>.  Let&#8217;s take some time and unpack the code. To gain access to Excel, we import <em>win32com.client</em> and then call its <em>gencache.EnsureDispatch</em>, passing in the application name that we want to open. In this case, the string to pass is &#8220;Excel.Application&#8221;. All that does is open Excel in the background. At this point, the user won&#8217;t even know Excel is open unless they have Task Manager running. The next line is adds a new workbook to Excel by calling that Excel instance&#8217;s &#8220;Workbooks.Add()&#8221; method. This returns a sheets object (I think). To get the ActiveSheet, we call <em>ss.ActiveSheet</em>. Finally, we make the Excel program itself visible by setting that property to True.</p>
<p>To set a specific cell&#8217;s value, call something like this: <em>sh.Cells(row,col).Value = &#8220;some value&#8221;</em>. Note that our instance is NOT zero-based and will actually put the value in the correct row/col combo. If we want to extract a value, we just remove the equals sign. What if we want the formula? To figure this our, I recorded a macro in Excel and did a Paste Special command that only pasted the Formula. Using the code generated, I figured out that to get the formula in Python, you just do this: </p>
<pre class="python">formula = sh.<span style="color: black;">Cells</span><span style="color: black;">&#40;</span>row, col<span style="color: black;">&#41;</span>.<span style="color: black;">Formula</span></pre>
<p>What if you need to change which sheet you&#8217;re on? Recording a macro also showed me how to accomplish this feat. Here&#8217;s the VBA code from Excel:</p>
<p><code><br />
Sub Macro1()<br />
'<br />
' Macro1 Macro<br />
'<br />
    Sheets(&quot;Sheet2&quot;).Select<br />
End Sub<br />
</code></p>
<p>From this code, I gathered that I needed to call my sheets object&#8217;s &#8220;Sheets&#8221; method and after a little fiddling, I got it to work by doing the following:</p>
<pre class="python">sheet2 = ss.<span style="color: black;">Sheets</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Sheet2&quot;</span><span style="color: black;">&#41;</span></pre>
<p>Now we have a handle on the second sheet in the workbook. If you want to edit or retrieve values, just prepend the same methods you used above with whatever you called the sheet2 instance (i.e. sheet2.Cells(1,1).Value). The last two lines from the original program will close the sheets and then quit the entire Excel instance.</p>
<p>You may be thinking that so far all I&#8217;ve shown is how to create a new document. What if you want to open an existing file? Just do something like this at the beginning of the code:</p>
<pre class="python">xl = win32.<span style="color: black;">gencache</span>.<span style="color: black;">EnsureDispatch</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Excel.Application'</span><span style="color: black;">&#41;</span>
ss = xl.<span style="color: black;">Workbooks</span>.<span style="color: black;">Open</span><span style="color: black;">&#40;</span>filename<span style="color: black;">&#41;</span></pre>
<p>And there you have it! You now know the basics of hacking Excel with Python using Excel&#8217;s COM object model. If you need to learn more, I recommend trying to record a macro and than translating the result into Python. <em>Note: I was unable to find an example that could save the spreadsheet&#8230;there are several examples that claim they work, but they didn&#8217;t for me.</em></p>
<h2>Python and Microsoft Word</h2>
<p>Accessing Microsoft Word with Python follows the same syntax that we used for Excel. Let&#8217;s take a quick look at how to access Word.</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">time</span> <span style="color: #ff7700;font-weight:bold;">import</span> sleep
<span style="color: #ff7700;font-weight:bold;">import</span> win32com.<span style="color: black;">client</span> as win32
&nbsp;
RANGE = <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">3</span>, <span style="color: #ff4500;">8</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> word<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    word = win32.<span style="color: black;">gencache</span>.<span style="color: black;">EnsureDispatch</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Word.Application'</span><span style="color: black;">&#41;</span>
    doc = word.<span style="color: black;">Documents</span>.<span style="color: black;">Add</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    word.<span style="color: black;">Visible</span> = <span style="color: #008000;">True</span>
    sleep<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
&nbsp;
    rng = doc.<span style="color: black;">Range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>,<span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
    rng.<span style="color: black;">InsertAfter</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Hacking Word with Python<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>'</span><span style="color: black;">&#41;</span>
    sleep<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> RANGE:
        rng.<span style="color: black;">InsertAfter</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'Line %d<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>'</span> <span style="color: #66cc66;">%</span> i<span style="color: black;">&#41;</span>
        sleep<span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
    rng.<span style="color: black;">InsertAfter</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>Python rules!<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
    doc.<span style="color: black;">Close</span><span style="color: black;">&#40;</span><span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
    word.<span style="color: black;">Application</span>.<span style="color: black;">Quit</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    word<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>This particular example is also based on something from Chun&#8217;s book as well. However, there are lots of other examples on the web that look almost exactly like this too. Let&#8217;s unpack this code now. To get a handle on the Microsoft Word application, we call <em>win32.gencache.EnsureDispatch(&#8216;Word.Application&#8217;)</em>; then we add a new document by calling the word instance&#8217;s <em>Documents.Add()</em>. If you want to show the user what you&#8217;re up to, you can set the visibility of Word to True.</p>
<p>If you want to add text to the document, then you&#8217;ll want to tell Word where you want the text to go. That&#8217;s where the Range method comes in. While you can&#8217;t see it, there is a &#8220;grid&#8221; of sorts that tells Word how to layout the text onscreen. So if we want to insert text at the very top of the document, we tell it to start at (0,0).  To add a new line in Word, we need to append &#8220;\r\n&#8221; to the end of our string. If you don&#8217;t know about the annoyances of line endings on different platforms, you should spend some time with Google and learn about it so you don&#8217;t get bit by weird bugs!</p>
<p>The rest of the code is pretty self-explanatory and will be left to the reader to interpret. We&#8217;ll move on to opening and saving documents now:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># Based on examples from http://code.activestate.com/recipes/279003/</span>
word.<span style="color: black;">Documents</span>.<span style="color: black;">Open</span><span style="color: black;">&#40;</span>doc<span style="color: black;">&#41;</span>
word.<span style="color: black;">ActiveDocument</span>.<span style="color: black;">SaveAs</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;c:<span style="color: #000099; font-weight: bold;">\\</span>a.txt&quot;</span>, FileFormat=win32com.<span style="color: black;">client</span>.<span style="color: black;">constants</span>.<span style="color: black;">wdFormatTextLineBreaks</span><span style="color: black;">&#41;</span></pre>
<p>Here we show how to open an existing Word document and save it as text. I haven&#8217;t tested this one fully, so your mileage may vary. If you want to read the text in the document, you can do the following:</p>
<pre class="python">docText = word.<span style="color: black;">Documents</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>.<span style="color: black;">Content</span></pre>
<p>And that ends the Python hacking lesson on Word documents. Since a lot of the information I was finding on Microsoft Word and Python was old and crusty and didn&#8217;t seem to work half the time, I don&#8217;t add to the mess of bad information. Hopefully this will get you started on your own journey into the wild wonders of Word manipulation.</p>
<h2>Further Reading</h2>
<ul>
<li><a href="http://win32com.goermezer.de/content/view/94/192/">Python for Windows Examples</a></li>
<li>Opening MS Word files via Python <a href="http://www.velocityreviews.com/forums/t330073-opening-ms-word-files-via-python.html">thread</a></li>
<li><a href="http://code.activestate.com/recipes/279003/">Recipe 279003</a>: Converting Word documents to text</li>
<li>Dzone: <a href="http://snippets.dzone.com/posts/show/2036">script excel from Python</a></li>
<li>Python-Excel <a href="http://www.python-excel.org/">website</a>, <a href="http://groups.google.com/group/python-excel">mailing list</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/07/16/python-and-microsoft-office-using-pywin32/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Python: How to Tell How Long Windows Has Been Idle</title>
		<link>http://www.blog.pythonlibrary.org/2010/05/05/python-how-to-tell-how-long-windows-has-been-idle/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/05/05/python-how-to-tell-how-long-windows-has-been-idle/#comments</comments>
		<pubDate>Wed, 05 May 2010 13:08:09 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[PyWin32]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=836</guid>
		<description><![CDATA[The other day, I received a request to create a script that could tell how long a Windows XP machine had been idle and to alert the user if it had been idle for a certain amount of time. I did a little research with Google and found a couple of ways to accomplish this [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/05/05/python-how-to-tell-how-long-windows-has-been-idle/" data-url="http://bit.ly/vUabkF" data-text="Python: How to Tell How Long Windows Has Been Idle" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/05/05/python-how-to-tell-how-long-windows-has-been-idle/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/05/05/python-how-to-tell-how-long-windows-has-been-idle/";
			reddit_title = "Python: How to Tell How Long Windows Has Been Idle";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/05/05/python-how-to-tell-how-long-windows-has-been-idle/"></g:plusone></div></div><p>The other day, I received a request to create a script that could tell how long a Windows XP machine had been idle and to alert the user if it had been idle for a certain amount of time. I did a little research with Google and found a couple of ways to accomplish this feat. The only one I was able to get working was a ctypes example, so without further ado, let&#8217;s check it out!<span id="more-836"></span></p>
<p>The following ctypes-related code was taken from a <a href="http://stackoverflow.com/questions/911856/detecting-idle-time-in-python">stackoverflow forum</a>:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> ctypes <span style="color: #ff7700;font-weight:bold;">import</span> Structure, windll, c_uint, sizeof, byref
&nbsp;
<span style="color: #808080; font-style: italic;"># http://stackoverflow.com/questions/911856/detecting-idle-time-in-python</span>
<span style="color: #ff7700;font-weight:bold;">class</span> LASTINPUTINFO<span style="color: black;">&#40;</span>Structure<span style="color: black;">&#41;</span>:
    _fields_ = <span style="color: black;">&#91;</span>
        <span style="color: black;">&#40;</span><span style="color: #483d8b;">'cbSize'</span>, c_uint<span style="color: black;">&#41;</span>,
        <span style="color: black;">&#40;</span><span style="color: #483d8b;">'dwTime'</span>, c_uint<span style="color: black;">&#41;</span>,
    <span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> get_idle_duration<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    lastInputInfo = LASTINPUTINFO<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    lastInputInfo.<span style="color: black;">cbSize</span> = sizeof<span style="color: black;">&#40;</span>lastInputInfo<span style="color: black;">&#41;</span>
    windll.<span style="color: black;">user32</span>.<span style="color: black;">GetLastInputInfo</span><span style="color: black;">&#40;</span>byref<span style="color: black;">&#40;</span>lastInputInfo<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    millis = windll.<span style="color: black;">kernel32</span>.<span style="color: black;">GetTickCount</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> - lastInputInfo.<span style="color: black;">dwTime</span>
    <span style="color: #ff7700;font-weight:bold;">return</span> millis / <span style="color: #ff4500;">1000.0</span></pre>
<p>If you don&#8217;t understand the code above, please ask for help on the ctypes mailing list. I don&#8217;t really understand it all either. I get the basic gist, but that&#8217;s it. Here&#8217;s the snippet I use to make the code above do its thing:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #ff4500;">1</span>:
    GetLastInputInfo = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>get_idle_duration<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> GetLastInputInfo
    <span style="color: #ff7700;font-weight:bold;">if</span> GetLastInputInfo == <span style="color: #ff4500;">480</span>:
        <span style="color: #808080; font-style: italic;"># if GetLastInputInfo is 8 minutes, play a sound</span>
        sound = r<span style="color: #483d8b;">&quot;c:<span style="color: #000099; font-weight: bold;">\w</span>indows<span style="color: #000099; font-weight: bold;">\m</span>edia<span style="color: #000099; font-weight: bold;">\n</span>otify.wav&quot;</span>
        <span style="color: #dc143c;">winsound</span>.<span style="color: black;">PlaySound</span><span style="color: black;">&#40;</span>sound, <span style="color: #dc143c;">winsound</span>.<span style="color: black;">SND_FILENAME</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> GetLastInputInfo == <span style="color: #ff4500;">560</span>:
        <span style="color: #808080; font-style: italic;"># if GetLastInputInfo is 9 minutes, play a more annoying sound</span>
        sound = r<span style="color: #483d8b;">&quot;c:<span style="color: #000099; font-weight: bold;">\w</span>indows<span style="color: #000099; font-weight: bold;">\m</span>edia<span style="color: #000099; font-weight: bold;">\r</span>ingout.wav&quot;</span>
        <span style="color: #dc143c;">winsound</span>.<span style="color: black;">PlaySound</span><span style="color: black;">&#40;</span>sound, <span style="color: #dc143c;">winsound</span>.<span style="color: black;">SND_FILENAME</span><span style="color: black;">&#41;</span>
        <span style="color: #dc143c;">winsound</span>.<span style="color: black;">PlaySound</span><span style="color: black;">&#40;</span>sound, <span style="color: #dc143c;">winsound</span>.<span style="color: black;">SND_FILENAME</span><span style="color: black;">&#41;</span>
        <span style="color: #dc143c;">winsound</span>.<span style="color: black;">PlaySound</span><span style="color: black;">&#40;</span>sound, <span style="color: #dc143c;">winsound</span>.<span style="color: black;">SND_FILENAME</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span></pre>
<p>In my code, I check if the machine has been idle for 8 minutes and 9 minutes. Depending on how long it&#8217;s been idle, the code plays a specific wav file with Python winsound module. In our shop, we have certain machines lock themselves if they&#8217;ve been idle for 10 minutes. Our users don&#8217;t like that too much, so they requested that we warn them with a sound when the machine was about to lock. That is what this script accomplishes. Hopefully you can find a better use for this knowledge.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/05/05/python-how-to-tell-how-long-windows-has-been-idle/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Restarting PCs with Python</title>
		<link>http://www.blog.pythonlibrary.org/2010/03/27/restarting-pcs-with-python/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/03/27/restarting-pcs-with-python/#comments</comments>
		<pubDate>Sat, 27 Mar 2010 15:47:25 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[System Administration]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[System Admin]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=738</guid>
		<description><![CDATA[Have you ever wanted to restart your Windows PC with out pressing Start, Shutdown or CTRL+ALT+DEL? What about restarting your annoying co-worker&#8217;s PC&#8230;the one who just doesn&#8217;t know when to shut up? Well, Python has the answer and this blog will tell you how to do it! Note: I don&#8217;t actually recommend rebooting your neighbor&#8217;s [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/03/27/restarting-pcs-with-python/" data-url="http://bit.ly/rWyHLZ" data-text="Restarting PCs with Python" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/03/27/restarting-pcs-with-python/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div><div class="socialize-in-button socialize-in-button-left"><script type="text/javascript">
			<!-- 
			reddit_url = "http://www.blog.pythonlibrary.org/2010/03/27/restarting-pcs-with-python/";
			reddit_title = "Restarting PCs with Python";	//-->
		</script><script type="text/javascript" src="http://www.reddit.com/static/button/button2.js"></script></div><div class="socialize-in-button socialize-in-button-left"><g:plusone size="small" href="http://www.blog.pythonlibrary.org/2010/03/27/restarting-pcs-with-python/"></g:plusone></div></div><p>Have you ever wanted to restart your Windows PC with out pressing Start, Shutdown or CTRL+ALT+DEL? What about restarting your annoying co-worker&#8217;s PC&#8230;the one who just doesn&#8217;t know when to shut up? Well, Python has the answer and this blog will tell you how to do it!<span id="more-738"></span> Note: I don&#8217;t actually recommend rebooting your neighbor&#8217;s PC at random&#8230;</p>
<h2>Rebooting with PyWin32</h2>
<p>Anyway, back when I was first learning about Python, I stumbled upon an ActiveState recipe on how to do this. Of course, now I can&#8217;t seem to find that recipe, but I found a similar one here: http://code.activestate.com/recipes/360649/. Thus, we&#8217;ll start with this method first and then look at a slightly different approach. If you&#8217;d like to follow along, then you&#8217;ll need to make sure you have the <a href="http://sourceforge.net/projects/pywin32/files/">PyWin32 package</a>.</p>
<p>Here&#8217;s my version of the recipe from my foggy past:</p>
<pre class="python"><span style="color: #808080; font-style: italic;"># rebootServer.py</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">import</span> win32security
<span style="color: #ff7700;font-weight:bold;">import</span> win32api
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">time</span>
<span style="color: #ff7700;font-weight:bold;">from</span> ntsecuritycon <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> AdjustPrivilege<span style="color: black;">&#40;</span>priv, enable=<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>:
    <span style="color: #808080; font-style: italic;"># Get the process token</span>
    flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY
    htoken = win32security.<span style="color: black;">OpenProcessToken</span><span style="color: black;">&#40;</span>win32api.<span style="color: black;">GetCurrentProcess</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, flags<span style="color: black;">&#41;</span>
    <span style="color: #808080; font-style: italic;"># Get the ID for the system shutdown privilege.</span>
    idd = win32security.<span style="color: black;">LookupPrivilegeValue</span><span style="color: black;">&#40;</span><span style="color: #008000;">None</span>, priv<span style="color: black;">&#41;</span>
    <span style="color: #808080; font-style: italic;"># Now obtain the privilege for this process.</span>
    <span style="color: #808080; font-style: italic;"># Create a list of the privileges to be added.</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> enable:
        newPrivileges = <span style="color: black;">&#91;</span><span style="color: black;">&#40;</span>idd, SE_PRIVILEGE_ENABLED<span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
    <span style="color: #ff7700;font-weight:bold;">else</span>:
        newPrivileges = <span style="color: black;">&#91;</span><span style="color: black;">&#40;</span>idd, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
    <span style="color: #808080; font-style: italic;"># and make the adjustment</span>
    win32security.<span style="color: black;">AdjustTokenPrivileges</span><span style="color: black;">&#40;</span>htoken, <span style="color: #ff4500;">0</span>, newPrivileges<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> RebootServer<span style="color: black;">&#40;</span>message=<span style="color: #483d8b;">'Rebooting'</span>, timeout=<span style="color: #ff4500;">30</span>, bForce=<span style="color: #ff4500;">0</span>, bReboot=<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>:
    AdjustPrivilege<span style="color: black;">&#40;</span>SE_SHUTDOWN_NAME<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        win32api.<span style="color: black;">InitiateSystemShutdown</span><span style="color: black;">&#40;</span><span style="color: #008000;">None</span>, message, timeout, bForce, bReboot<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">finally</span>:
        <span style="color: #808080; font-style: italic;"># Now we remove the privilege we just added.</span>
        AdjustPrivilege<span style="color: black;">&#40;</span>SE_SHUTDOWN_NAME, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> AbortReboot<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
    AdjustPrivilege<span style="color: black;">&#40;</span>SE_SHUTDOWN_NAME<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        win32api.<span style="color: black;">AbortSystemShotdown</span><span style="color: black;">&#40;</span><span style="color: #008000;">None</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">finally</span>:
        AdjustPrivilege<span style="color: black;">&#40;</span>SE_SHUTDOWN_NAME, <span style="color: #ff4500;">0</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    RebootServer<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">time</span>.<span style="color: black;">sleep</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Aborting shutdown'</span>
    AbortReboot<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>I actually took out the ability to reboot remote machines in this snippet just because I didn&#8217;t want to be tempted to do so. If you want to reboot a machine on your network, change the following line:</p>
<pre class="python">win32api.<span style="color: black;">InitiateSystemShutdown</span><span style="color: black;">&#40;</span><span style="color: #008000;">None</span>, message, timeout, bForce, bReboot<span style="color: black;">&#41;</span></pre>
<p>to</p>
<pre class="python">win32api.<span style="color: black;">InitiateSystemShutdown</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;someMachineName&quot;</span>, message, timeout, bForce, bReboot<span style="color: black;">&#41;</span></pre>
<p>or just add a host parameter to the <em>RebootServer</em> function and modify the InitiateSystemShutdown as necessary. If you just pass <em>None </em>in, then you&#8217;ll just reboot your own machine. The <em>AdjustPrivilege</em> method is used to change the privilege of the process so that it can actually shut the PC down. I think that only applies if you run the script as a user with limited privileges, but I almost never run that way so I can&#8217;t be sure. I do remember the recipe stating that you needed to remove the privileges that you added, which is what the <em>finally</em> statement is for. However, I would assume that once the reboot is complete, those privileges would have been revoked anyway.</p>
<h2>Rebooting with just Plain Ol&#8217; Python</h2>
<p>The other way to initiate a shutdown is to learn the magic of your Windows command line. There is a shutdown command that you can put into your Run dialog (go to Start &#8211;> Run) that will reboot your PC too. Here&#8217;s the one I&#8217;m talking about:  shutdown -r -t 1   <em>Note that this will only restart the local machine!</em></p>
<p>Now we just need to figure out how to make Python call that for us. Probably the simplest way to do so is to import the <em>os</em> module and call its <em>system</em> method. Let&#8217;s take a look:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #dc143c;">os</span>.<span style="color: black;">system</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;shutdown -r -t 1&quot;</span><span style="color: black;">&#41;</span></pre>
<p>This is much shorter than the PyWin32 method, but I don&#8217;t know that it&#8217;s as robust. I used this method in a quick and dirty wxPython application I created for our Sun Ray virtual machines at work. One of the biggest problems with the Sun Ray system is that the user is connected to their virtual machine using Remote Desktop. A part of Remote Desktop is to hide the Shutdown button, so there is no simple way for the user to restart their PC unless they&#8217;re installed some kind of hotfix that does it for them. There are times when rebooting a machine is a good thing, so I took the script above and put it into the following application:</p>
<p><a href="http://www.blog.pythonlibrary.org/wp-content/uploads/2010/03/restarter.png"><img src="http://www.blog.pythonlibrary.org/wp-content/uploads/2010/03/restarter.png" alt="" title="restarter" width="273" height="169" class="aligncenter size-full wp-image-739" /></a></p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #ff7700;font-weight:bold;">import</span> wx
<span style="color: #ff7700;font-weight:bold;">from</span> wx.<span style="color: black;">lib</span>.<span style="color: black;">buttons</span> <span style="color: #ff7700;font-weight:bold;">import</span> GenBitmapButton
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> RestarterPanel<span style="color: black;">&#40;</span>wx.<span style="color: black;">Panel</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, parent<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        wx.<span style="color: black;">Panel</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, parent=parent<span style="color: black;">&#41;</span>
&nbsp;
        img = wx.<span style="color: black;">Bitmap</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;cute-logoff.png&quot;</span><span style="color: black;">&#41;</span>
        logoutBtn = GenBitmapButton<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, wx.<span style="color: black;">ID_ANY</span>, img, style=wx.<span style="color: black;">BORDER_NONE</span><span style="color: black;">&#41;</span>
        logoutBtn.<span style="color: black;">Bind</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">EVT_BUTTON</span>, <span style="color: #008000;">self</span>.<span style="color: black;">onLogout</span><span style="color: black;">&#41;</span>
&nbsp;
        img = wx.<span style="color: black;">Bitmap</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;quick_restart.png&quot;</span><span style="color: black;">&#41;</span>
        restartBtn = GenBitmapButton<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, wx.<span style="color: black;">ID_ANY</span>, img, style=wx.<span style="color: black;">BORDER_NONE</span><span style="color: black;">&#41;</span>
        restartBtn.<span style="color: black;">Bind</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">EVT_BUTTON</span>, <span style="color: #008000;">self</span>.<span style="color: black;">onRestart</span><span style="color: black;">&#41;</span>
&nbsp;
        cancelBtn = wx.<span style="color: black;">Button</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=<span style="color: #483d8b;">&quot;Cancel&quot;</span><span style="color: black;">&#41;</span>
        cancelBtn.<span style="color: black;">Bind</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">EVT_BUTTON</span>, <span style="color: #008000;">self</span>.<span style="color: black;">onCancel</span><span style="color: black;">&#41;</span>
&nbsp;
        vSizer = wx.<span style="color: black;">BoxSizer</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">VERTICAL</span><span style="color: black;">&#41;</span>
        sizer = wx.<span style="color: black;">BoxSizer</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">HORIZONTAL</span><span style="color: black;">&#41;</span>
        sizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">buttonBuilder</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Logout&quot;</span>, logoutBtn<span style="color: black;">&#41;</span>, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">CENTER</span><span style="color: black;">&#41;</span>
        sizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">buttonBuilder</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;Restart&quot;</span>, restartBtn<span style="color: black;">&#41;</span>, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">CENTER</span><span style="color: black;">&#41;</span>
        vSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>sizer, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">CENTER</span><span style="color: black;">&#41;</span>
        vSizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>cancelBtn, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALIGN_RIGHT</span>|wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">SetSizer</span><span style="color: black;">&#40;</span>vSizer<span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> buttonBuilder<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label, button<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Creates a button with a label underneath it and puts them into
        a vertical BoxSizer, which is then returned
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        font = wx.<span style="color: black;">Font</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">12</span>, wx.<span style="color: black;">SWISS</span>, wx.<span style="color: black;">NORMAL</span>, wx.<span style="color: black;">BOLD</span><span style="color: black;">&#41;</span>
        sizer = wx.<span style="color: black;">BoxSizer</span><span style="color: black;">&#40;</span>wx.<span style="color: black;">VERTICAL</span><span style="color: black;">&#41;</span>
        sizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>button, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">ALL</span>, <span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>
&nbsp;
        lbl = wx.<span style="color: black;">StaticText</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, label=label<span style="color: black;">&#41;</span>
        lbl.<span style="color: black;">SetFont</span><span style="color: black;">&#40;</span>font<span style="color: black;">&#41;</span>
        sizer.<span style="color: black;">Add</span><span style="color: black;">&#40;</span>lbl, <span style="color: #ff4500;">0</span>, wx.<span style="color: black;">CENTER</span>|wx.<span style="color: black;">BOTTOM</span>, <span style="color: #ff4500;">4</span><span style="color: black;">&#41;</span>
&nbsp;
        <span style="color: #ff7700;font-weight:bold;">return</span> sizer
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> onCancel<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Close the dialog
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">GetParent</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">Close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> onLogout<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Logs the current user out
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #dc143c;">os</span>.<span style="color: black;">system</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;shutdown -t 0 -l&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> onRestart<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, event<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;
        Restarts the PC
        &quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        <span style="color: #dc143c;">os</span>.<span style="color: black;">system</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;shutdown -r -t 1&quot;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> RestarterFrame<span style="color: black;">&#40;</span>wx.<span style="color: black;">Frame</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        wx.<span style="color: black;">Frame</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, <span style="color: #008000;">None</span>, size=<span style="color: black;">&#40;</span><span style="color: #ff4500;">273</span>, <span style="color: #ff4500;">169</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        panel = RestarterPanel<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">Center</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">########################################################################</span>
<span style="color: #ff7700;font-weight:bold;">class</span> Main<span style="color: black;">&#40;</span>wx.<span style="color: black;">App</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, redirect=<span style="color: #008000;">False</span>, filename=<span style="color: #008000;">None</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">&quot;&quot;</span><span style="color: #483d8b;">&quot;Constructor&quot;</span><span style="color: #483d8b;">&quot;&quot;</span>
        wx.<span style="color: black;">App</span>.<span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, redirect, filename<span style="color: black;">&#41;</span>
        dlg = RestarterFrame<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        dlg.<span style="color: black;">Show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">#----------------------------------------------------------------------</span>
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">&quot;__main__&quot;</span>:
    app = Main<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    app.<span style="color: black;">MainLoop</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre>
<p>I looked at a lot of icons for this project and I think I ended up just doing searches for <a href="http://commons.wikimedia.org/wiki/File:Quick_restart.png">shutdown </a>and <a href="http://www.iconfinder.net/icondetails/32136/128/?q=cute">logout </a>icons and downloaded the ones I liked the best. Both of these free or had Creative Commons licenses.</p>
<p>Now you know the tricks to restart local and remote machines. Use this knowledge wisely!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/03/27/restarting-pcs-with-python/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Python&#8217;s _winreg: Editing the Windows Registry</title>
		<link>http://www.blog.pythonlibrary.org/2010/03/20/pythons-_winreg-editing-the-windows-registry/</link>
		<comments>http://www.blog.pythonlibrary.org/2010/03/20/pythons-_winreg-editing-the-windows-registry/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 12:26:30 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[System Administration]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Registry]]></category>
		<category><![CDATA[System Admin]]></category>

		<guid isPermaLink="false">http://www.blog.pythonlibrary.org/?p=698</guid>
		<description><![CDATA[Python&#8217;s standard library is known for including lots of handy modules and packages that can be used without installing anything else. That&#8217;s one of the primary reasons that its standard library is called &#8220;batteries included&#8221; so often. So it should come as no surprise that Python includes a Windows only module for editing the Windows [...]]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-counturl="http://www.blog.pythonlibrary.org/2010/03/20/pythons-_winreg-editing-the-windows-registry/" data-url="http://bit.ly/vHisL5" data-text="Python&#8217;s _winreg: Editing the Windows Registry" data-count="vertical" data-via="socializeWP" ><!--Tweetter--></a></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://www.blog.pythonlibrary.org/2010/03/20/pythons-_winreg-editing-the-windows-registry/&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Python&#8217;s standard library is known for including lots of handy modules and packages that can be used without installing anything else. That&#8217;s one of the primary reasons that its standard library is called &#8220;batteries included&#8221; so often. So it should come as no surprise that Python includes a Windows only module for editing the Windows Registry. This particular module goes by the odd name of <em>_winreg</em> (odd because it starts with an underscore). In this article, we&#8217;ll learn the basics of working with the Registry using this &#8220;battery&#8221;. <span id="more-698"></span></p>
<h2>Reading from the Registry</h2>
<p>Using Python to read data from the registry is very easy. In the following example, we&#8217;ll find out where Outlook Express is installed:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">_winreg</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #66cc66;">*</span>
key = OpenKey<span style="color: black;">&#40;</span>HKEY_LOCAL_MACHINE, r<span style="color: #483d8b;">'Software<span style="color: #000099; font-weight: bold;">\M</span>icrosoft<span style="color: #000099; font-weight: bold;">\O</span>utlook Express'</span>, <span style="color: #ff4500;">0</span>, KEY_ALL_ACCESS<span style="color: black;">&#41;</span>
QueryValueEx<span style="color: black;">&#40;</span>key, <span style="color: #483d8b;">&quot;InstallRoot&quot;</span><span style="color: black;">&#41;</span></pre>
<p>On my machine, this will return the following tuple: (u&#8217;%ProgramFiles%\\Outlook Express&#8217;, 2). The tuple is made up of the value and the registry type of said value. There are two other query methods that one can use called QueryInfoKey and QueryValue. The former gives you information about the key itself in form of three integers while the latter retrieves only the data for a key’s first value that has a NULL name. The <a href="http://docs.python.org/library/_winreg.html">documentation</a> recommends that you use QueryValueEx whenever possible. </p>
<p>We should probably quickly explain what&#8217;s going on in the code above as well. The OpenKey function takes an HKEY* constant, a subkey path string, a reserved integer (which must be zero) and the security mask. In this case, we passed in KEY_ALL_ACCESS which gives us complete control of that key. Since all we were doing was reading it, we probably should have just used KEY_READ though. As for what QueryValueEx does, it just accepts a key object and the field name that we want to query against.</p>
<h2>Writing to the Registry</h2>
<p>If you&#8217;ve been reading this blog lately, then you&#8217;ve probably already seen the _winreg module used for writing to the registry. This will just be review for you, so feel free to skip this section. We&#8217;ll start out with a practical example. In the following code snippet, we will set Internet Explorer&#8217;s home page. As always, please note that editing Registry entries can be dangerous. <strong>IMPORTANT: Be sure to back up your registry before attempting to edit it.</strong> Now, on with the show!</p>
<pre class="python">keyVal = r<span style="color: #483d8b;">'Software<span style="color: #000099; font-weight: bold;">\M</span>icrosoft<span style="color: #000099; font-weight: bold;">\I</span>nternet Explorer<span style="color: #000099; font-weight: bold;">\M</span>ain'</span>
<span style="color: #ff7700;font-weight:bold;">try</span>:
    key = OpenKey<span style="color: black;">&#40;</span>HKEY_CURRENT_USER, keyVal, <span style="color: #ff4500;">0</span>, KEY_ALL_ACCESS<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">except</span>:
    key = CreateKey<span style="color: black;">&#40;</span>HKEY_CURRENT_USER, keyVal<span style="color: black;">&#41;</span>
SetValueEx<span style="color: black;">&#40;</span>key, <span style="color: #483d8b;">&quot;Start Page&quot;</span>, <span style="color: #ff4500;">0</span>, REG_SZ, <span style="color: #483d8b;">&quot;http://www.blog.pythonlibrary.org/&quot;</span><span style="color: black;">&#41;</span>
CloseKey<span style="color: black;">&#40;</span>key<span style="color: black;">&#41;</span></pre>
<p>In the code above, we attempt to open the following key: <em>HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main</em> and set the &#8220;Start Page&#8221; value to this blog. If the open fails, it&#8217;s usually because the key doesn&#8217;t exist, so we try to create the key in our exception handler. Then we use SetValueEx to actually set the value and like all good programmers, we clean up when we&#8217;re done and close the key. If you skipped the CloseKey command, you&#8217;d be fine in this case as the script is done and Python will do it for you. However, if you continued working on this key, you might have an access violation since it&#8217;s already open. Thus, the lesson is to always close a key when you finish editing it.</p>
<h2>Other _winreg Methods</h2>
<p>There are several other methods in the _winreg library worth pointing out. The DeleteKey method is handy when you need to remove a key. Unfortunately, I&#8217;ve had occasion when I need to remove keys recursively, such as when an uninstall goes bad and _winreg has no built-in way of doing that. You can write your own, of course, or you can download a wrapper like <a href="http://code.activestate.com/recipes/476229-yarw-yet-another-registry-wrapper/">YARW</a> (Yet Another Registry Wrapper) that can do it for you.</p>
<p>DeleteValue is similar to DeleteKey, except that you delete just a value. Yes, it&#8217;s pretty obvious. If you&#8217;d wanted to write your own recursive key deleting code, then you&#8217;d probably want to take a look at EnumKey and EnumValue as they enumerate keys and values respectively. Let&#8217;s take a quick look at how to use EnumKey:</p>
<pre class="python"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">_winreg</span> <span style="color: #ff7700;font-weight:bold;">import</span> EnumKey, HKEY_USERS
&nbsp;
<span style="color: #ff7700;font-weight:bold;">try</span>:
    i = <span style="color: #ff4500;">0</span>
    <span style="color: #ff7700;font-weight:bold;">while</span> <span style="color: #008000;">True</span>:
        subkey = EnumKey<span style="color: black;">&#40;</span>HKEY_USERS, i<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">print</span> subkey
        i += <span style="color: #ff4500;">1</span>
<span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">WindowsError</span>:
    <span style="color: #808080; font-style: italic;"># WindowsError: [Errno 259] No more data is available    </span>
    <span style="color: #ff7700;font-weight:bold;">pass</span></pre>
<p>The code above will loop through the HKEY_USERS hive printing the subkey to stdout until we reach the end of the hive and a WindowsError is raised. Of course, this does not descend into the subkeys, but I&#8217;ll leave that as an exercise for the reader to figure out.</p>
<p>The last method that we&#8217;ll talk about here is ConnectRegistry. This is helpful if we need to edit the Registry of a remote machine. It only accepts two arguments: the computer name and the key to connect to (i.e. HKEY_LOCAL_MACHINE or some such). Note that when connecting to remote machines, you can only edit certain keys while the others are unavailable. </p>
<h2>Wrapping Up</h2>
<p>I hope this was helpful for you and that it gave you lots of good ideas for your future projects. I have many login scripts that use this wonderful library and a couple that use YARW. It&#8217;s been quite useful so far and I hope that it will be the same for you.</p>
<p><strong>UPDATE (10/14/2011):</strong> We now have a Brazilian Portuguese translation of this post up on Carlisson Galdino&#8217;s <a href="http://www.carlissongaldino.com.br/post/editando-o-registro-do-windows-em-python-com-o-winreg" target="_blank">blog </a></p>
<h2>Further Reading</h2>
<ul>
<li><a href="http://docs.python.org/library/_winreg.html">Official documentation for _winreg</a></li>
<li><a href="http://effbot.org/librarybook/winreg.htm">Effbot tutorial on _winreg</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.pythonlibrary.org/2010/03/20/pythons-_winreg-editing-the-windows-registry/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 4.960 seconds -->

