title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Interface for modifying Windows environment variables from Python
1,085,852
<p>How can I persistently modify the Windows environment variables from a Python script? (it's the setup.py script)</p> <p>I'm looking for a standard function or module to use for this. I'm already familiar with the <a href="http://code.activestate.com/recipes/416087/">registry way of doing it</a>, but any comments regarding that are also welcome.</p>
15
2009-07-06T07:48:40Z
1,085,879
<p>The registry way is if you want to modify it permanently for everything, which I guess is what you want here since it's in setup.py.</p> <p>Temporarily for just your process, then os.environ is the trick.</p>
1
2009-07-06T07:59:19Z
[ "python", "windows", "environment-variables" ]
Interface for modifying Windows environment variables from Python
1,085,852
<p>How can I persistently modify the Windows environment variables from a Python script? (it's the setup.py script)</p> <p>I'm looking for a standard function or module to use for this. I'm already familiar with the <a href="http://code.activestate.com/recipes/416087/">registry way of doing it</a>, but any comments regarding that are also welcome.</p>
15
2009-07-06T07:48:40Z
1,085,950
<p>In the os module, there is getenv and putenv functions. However, it seems that the putenv is not working correctly and that you must use the windows registry instead</p> <p>Look at <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/60a59bbf8207aeb0/4e9e51c84dc7a01f" rel="nofollow"> this discussion</a> </p>
1
2009-07-06T08:18:44Z
[ "python", "windows", "environment-variables" ]
Interface for modifying Windows environment variables from Python
1,085,852
<p>How can I persistently modify the Windows environment variables from a Python script? (it's the setup.py script)</p> <p>I'm looking for a standard function or module to use for this. I'm already familiar with the <a href="http://code.activestate.com/recipes/416087/">registry way of doing it</a>, but any comments regarding that are also welcome.</p>
15
2009-07-06T07:48:40Z
1,086,098
<p>It may be just as easy to use the external Windows <code>setx</code> command:</p> <pre><code>C:\&gt;set NEWVAR Environment variable NEWVAR not defined C:\&gt;python Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.system('setx NEWVAR newvalue') 0 &gt;&gt;&gt; os.getenv('NEWVAR') &gt;&gt;&gt; ^Z C:\&gt;set NEWVAR Environment variable NEWVAR not defined </code></pre> <p>Now open a new Command Prompt:</p> <pre><code>C:\&gt;set NEWVAR NEWVAR=newvalue </code></pre> <p>As you can see, <code>setx</code> neither sets the variable for the current session, nor for the parent process (the first Command Prompt). But it does set the variable persistently in the registry for future processes.</p> <p>I don't think there is a way of changing the parent process's environment at all (and if there is, I'd love to hear it!).</p>
4
2009-07-06T08:59:42Z
[ "python", "windows", "environment-variables" ]
Interface for modifying Windows environment variables from Python
1,085,852
<p>How can I persistently modify the Windows environment variables from a Python script? (it's the setup.py script)</p> <p>I'm looking for a standard function or module to use for this. I'm already familiar with the <a href="http://code.activestate.com/recipes/416087/">registry way of doing it</a>, but any comments regarding that are also welcome.</p>
15
2009-07-06T07:48:40Z
1,146,404
<p>Using setx has few drawbacks, especially if you're trying to append to environment variables (eg. setx PATH %Path%;C:\mypath) This will repeatedly append to the path every time you run it, which can be a problem. Worse, it doesn't distinguish between the machine path (stored in HKEY_LOCAL_MACHINE), and the user path, (stored in HKEY_CURRENT_USER). The environment variable you see at a command prompt is made up of a concatenation of these two values. Hence, before calling setx:</p> <pre><code>user PATH == u machine PATH == m %PATH% == m;u &gt; setx PATH %PATH%;new Calling setx sets the USER path by default, hence now: user PATH == m;u;new machine PATH == m %PATH% == m;m;u;new </code></pre> <p>The system path is unavoidably duplicated in the %PATH% environment variable every time you call setx to append to PATH. These changes are permanent, never reset by reboots, and so accumulate through the life of the machine.</p> <p>Trying to compensate for this in DOS is beyond my ability. So I turned to Python. The solution I have come up with today, to set environment variables by tweaking the registry, including appending to PATH without introducing duplicates, is as follows:</p> <pre><code>from os import system, environ import win32con from win32gui import SendMessage from _winreg import ( CloseKey, OpenKey, QueryValueEx, SetValueEx, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS, KEY_READ, REG_EXPAND_SZ, REG_SZ ) def env_keys(user=True): if user: root = HKEY_CURRENT_USER subkey = 'Environment' else: root = HKEY_LOCAL_MACHINE subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' return root, subkey def get_env(name, user=True): root, subkey = env_keys(user) key = OpenKey(root, subkey, 0, KEY_READ) try: value, _ = QueryValueEx(key, name) except WindowsError: return '' return value def set_env(name, value): key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS) SetValueEx(key, name, 0, REG_EXPAND_SZ, value) CloseKey(key) SendMessage( win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') def remove(paths, value): while value in paths: paths.remove(value) def unique(paths): unique = [] for value in paths: if value not in unique: unique.append(value) return unique def prepend_env(name, values): for value in values: paths = get_env(name).split(';') remove(paths, '') paths = unique(paths) remove(paths, value) paths.insert(0, value) set_env(name, ';'.join(paths)) def prepend_env_pathext(values): prepend_env('PathExt_User', values) pathext = ';'.join([ get_env('PathExt_User'), get_env('PathExt', user=False) ]) set_env('PathExt', pathext) set_env('Home', '%HomeDrive%%HomePath%') set_env('Docs', '%HomeDrive%%HomePath%\docs') set_env('Prompt', '$P$_$G$S') prepend_env('Path', [ r'%SystemDrive%\cygwin\bin', # Add cygwin binaries to path r'%HomeDrive%%HomePath%\bin', # shortcuts and 'pass-through' bat files r'%HomeDrive%%HomePath%\docs\bin\mswin', # copies of standalone executables ]) # allow running of these filetypes without having to type the extension prepend_env_pathext(['.lnk', '.exe.lnk', '.py']) </code></pre> <p>It does not affect the current process or the parent shell, but it will affect all cmd windows opened after it is run, without needing a reboot, and can safely be edited and re-run many times without introducing any duplicates.</p>
17
2009-07-18T01:25:12Z
[ "python", "windows", "environment-variables" ]
Interface for modifying Windows environment variables from Python
1,085,852
<p>How can I persistently modify the Windows environment variables from a Python script? (it's the setup.py script)</p> <p>I'm looking for a standard function or module to use for this. I'm already familiar with the <a href="http://code.activestate.com/recipes/416087/">registry way of doing it</a>, but any comments regarding that are also welcome.</p>
15
2009-07-06T07:48:40Z
1,179,789
<p>It must have been a millennium ago that I've tried to change the environment of the current DOS session by means of a program. The problem is: that program runs within its own DOS shell, so it has to operate on its parent environment. It takes a walk, starting at the DOS Info Block, all along the chain of Memory Control Blocks, to find the location of that parent environment. Once I had found out how to do this, my need for manipulating environment variables had vanished. I'll give you the Turbo Pascal code below, but I guess there are at least three better ways to do the trick:</p> <ol> <li><p>Create a batch file that: <em>(a)</em> calls a Python script (or whatever) that generates a temporay batch file containing the appropriate SET commands; <em>(b)</em> calls the temporary batch file (the SET commands are executed in the current shell); and <em>(c)</em> removes the temporary batch file.</p></li> <li><p>Create a Python script that writes something like "VAR1=val1\nVAR2=val2\nVAR3=val3\n" to STDOUT. Use it this way in your batch file:</p> <p><code>for /f "delims=|" %%X in ('</code><em>callYourPythonScript</em><code>') do set %%X</code></p> <p>et voilà: variables VAR1, VAR2 and VAR3 have been given a value.</p></li> <li><p>Modify the Windows Registry and broadcast the setting change as described <a href="http://stackoverflow.com/questions/190168/persisting-an-environment-variable-through-ruby">here</a> by Alexander Prokofyev.</p></li> </ol> <p>And here goes the Pascal code (you may need a Dutch dictionary and a Pascal programming book) of a program that just reports memory locations. It still seems to work under Windows XP, be it reporting we're running DOS 5.00. This is only a first beginning, there's a lot of low level programming to do in order to manipulate the selected environment. And as the pointer structure may seem correct, I'm not so sure if the environment model of 1994 still holds these days...</p> <pre><code>program MCBKETEN; uses dos, HexConv; {----------------------------------------------------------------------------} { Programma: MCBKETEN.EXE } { Broncode : MCBKETEN.PAS } { Doel : Tocht langs de MCB's met rapportage } { Datum : 11 januari 1994 } { Auteur : Meindert Meindertsma } { Versie : 1.00 } {----------------------------------------------------------------------------} type MCB_Ptr = ^MCB; { MCB_PtrPtr = ^MCB_Ptr; vervallen wegens DOS 2.11 -- zie verderop } MCB = record Signatuur : char; Eigenaar : word; Paragrafen : word; Gereserveerd : array[1..3] of byte; Naam : array[1..8] of char; end; BlokPtr = ^BlokRec; BlokRec = record Vorige : BlokPtr; DitSegment, Paragrafen : word; Signatuur : string[6]; Eigenaar, Omgeving : word; Functie : String4; Oorsprong, Pijl : char; KorteNaam : string[8]; LangeNaam : string; Volgende : BlokPtr; end; PSP_Ptr = ^PSP; PSP = record Vulsel1 : array[1..44] of byte; Omgeving : word; Vulsel2 : array[47..256] of byte; end; var Zone : string[5]; ProgGevonden, EindeKeten, Dos3punt2 : boolean; Regs : registers; ActMCB : MCB_Ptr; EersteSchakel, Schakel, LaatsteSchakel : BlokPtr; ActPSP : PSP_Ptr; EersteProg, Meester, Ouder, TerugkeerSegment, TerugkeerOffset, TerugkeerSegment2, OuderSegment : word; Specificatie : string[8]; ReleaseNummer : string[2]; i : byte; {----------------------------------------------------------------------------} { PROCEDURES EN FUNCTIES } {----------------------------------------------------------------------------} function Coda (Omgeving : word; Paragrafen : word) : string; var i : longint; Vorige, Deze : char; Streng : string; begin i := 0; Deze := #0; repeat Vorige := Deze; Deze := char (ptr (Omgeving, i)^); inc (i); until ((Vorige = #0) and (Deze = #0)) or (i div $10 >= Paragrafen); if (i + 3) div $10 &lt; Paragrafen then begin Vorige := char (ptr (Omgeving, i)^); inc (i); Deze := char (ptr (Omgeving, i)^); inc (i); if (Vorige = #01) and (Deze = #0) then begin Streng := ''; Deze := char (ptr (Omgeving, i)^); inc (i); while (Deze &lt;> #0) and (i div $10 &lt; Paragrafen) do begin Streng := Streng + Deze; Deze := char (ptr (Omgeving, i)^); inc (i); end; Coda := Streng; end else Coda := ''; end else Coda := ''; end {Coda}; {----------------------------------------------------------------------------} { HOOFDPROGRAMMA } {----------------------------------------------------------------------------} BEGIN {----- Initiatie -----} Zone := 'Lower'; ProgGevonden := FALSE; EindeKeten := FALSE; Dos3punt2 := (dosversion >= $1403) and (dosversion &lt;= $1D03); Meester := $0000; Ouder := $0000; Specificatie[0] := #8; str (hi (dosversion) : 2, ReleaseNummer); if ReleaseNummer[1] = ' ' then ReleaseNummer[1] := '0'; {----- Pointer naar eerste MCB ophalen ------} Regs.AH := $52; { functie $52 geeft adres van DOS Info Block in ES:BX } msdos (Regs); { ActMCB := MCB_PtrPtr (ptr (Regs.ES, Regs.BX - 4))^; NIET onder DOS 2.11 } ActMCB := ptr (word (ptr (Regs.ES, Regs.BX - 2)^), $0000); {----- MCB-keten doorlopen -----} new (EersteSchakel); EersteSchakel^.Vorige := nil; Schakel := EersteSchakel; repeat with Schakel^ do begin DitSegment := seg (ActMCB^); Paragrafen := ActMCB^.Paragrafen; if DitSegment + Paragrafen >= $A000 then Zone := 'Upper'; Signatuur := Zone + ActMCB^.Signatuur; Eigenaar := ActMCB^.Eigenaar; ActPSP := ptr (Eigenaar, 0); if not ProgGevonden then EersteProg := DitSegment + 1; if Eigenaar >= EersteProg then Omgeving := ActPSP^.Omgeving else Omgeving := 0; if DitSegment + 1 = Eigenaar then begin ProgGevonden := TRUE; Functie := 'Prog'; KorteNaam[0] := #0; while (ActMCB^.Naam[ ord (KorteNaam[0]) + 1 ] &lt;> #0) and (KorteNaam[0] &lt; #8) do begin inc (KorteNaam[0]); KorteNaam[ ord (KorteNaam[0]) ] := ActMCB^.Naam[ ord (KorteNaam[0]) ]; end; if Eigenaar = prefixseg then begin TerugkeerSegment := word (ptr (prefixseg, $000C)^); TerugkeerOffset := word (ptr (prefixseg, $000A)^); LangeNaam := '-----> Terminate Vector = ' + WordHex (TerugkeerSegment) + ':' + WordHex (TerugkeerOffset ) ; end else LangeNaam := ''; end {if ÆProgØ} else begin if Eigenaar = $0008 then begin if ActMCB^.Naam[1] = 'S' then case ActMCB^.Naam[2] of 'D' : Functie := 'SysD'; 'C' : Functie := 'SysP'; else Functie := 'Data'; end {case} else Functie := 'Data'; KorteNaam := ''; LangeNaam := ''; end {if Eigenaar = $0008} else begin if DitSegment + 1 = Omgeving then begin Functie := 'Env '; LangeNaam := Coda (Omgeving, Paragrafen); if EersteProg = Eigenaar then Meester := Omgeving; end {if ÆEnvØ} else begin move (ptr (DitSegment + 1, 0)^, Specificatie[1], 8); if (Specificatie = 'PATH=' + #0 + 'CO') or (Specificatie = 'COMSPEC=' ) or (Specificatie = 'OS=DRDOS' ) then begin Functie := 'Env' + chr (39); LangeNaam := Coda (DitSegment + 1, Paragrafen); if (EersteProg = Eigenaar) and (Meester = $0000 ) then Meester := DitSegment + 1; end else begin if Eigenaar = 0 then Functie := 'Free' else Functie := 'Data'; LangeNaam := ''; if (EersteProg = Eigenaar) and (Meester = $0000 ) then Meester := DitSegment + 1; end; end {else: not ÆEnvØ}; KorteNaam := ''; end {else: Eigenaar &lt;> $0008}; end {else: not ÆProgØ}; {----- KorteNaam redigeren -----} for i := 1 to length (KorteNaam) do if KorteNaam[i] &lt; #32 then KorteNaam[i] := '.'; KorteNaam := KorteNaam + ' '; {----- Oorsprong vaststellen -----} if EersteProg = Eigenaar then Oorsprong := '*' else Oorsprong := ' '; {----- Actueel proces (uitgaande Pijl) vaststellen -----} if Eigenaar = prefixseg then Pijl := '>' else Pijl := ' '; end {with Schakel^}; {----- MCB-opeenvolging onderzoeken / schakelverloop vaststellen -----} if (Zone = 'Upper') and (ActMCB^.Signatuur = 'Z') then begin Schakel^.Volgende := nil; EindeKeten := TRUE; end else begin ActMCB := ptr (seg (ActMCB^) + ActMCB^.Paragrafen + 1, 0); if ((ActMCB^.Signatuur &lt;> 'M') and (ActMCB^.Signatuur &lt;> 'Z')) or ($FFFF - ActMCB^.Paragrafen &lt; seg (ActMCB^) ) then begin Schakel^.Volgende := nil; EindeKeten := TRUE; end else begin new (LaatsteSchakel); Schakel^.Volgende := LaatsteSchakel; LaatsteSchakel^.Vorige := Schakel; Schakel := LaatsteSchakel; end {else: (ÆMØ or ÆZØ) and Æteveel_ParagrafenØ}; end {else: ÆLowerØ or not ÆZØ}; until EindeKeten; {----- Terugtocht -----} while Schakel &lt;> nil do with Schakel^ do begin {----- Ouder-proces vaststellen -----} TerugkeerSegment2 := TerugkeerSegment + (TerugkeerOffset div $10); if (DitSegment &lt;= TerugkeerSegment2) and (DitSegment + Paragrafen >= TerugkeerSegment2) then OuderSegment := Eigenaar; {----- Meester-omgeving markeren -----} if DitSegment + 1 = Meester then Oorsprong := 'M'; {----- Schakel-verloop -----} Schakel := Schakel^.Vorige; end {while Schakel &lt;> nil}; {----- Rapportage -----} writeln ('Chain of Memory Control Blocks in DOS version ', lo (dosversion), '.', ReleaseNummer, ':'); writeln; writeln ('MCB@ #Par Signat PSP@ Env@ Type !! Name File'); writeln ('---- ---- ------ ---- ---- ---- -- -------- ', '-----------------------------------'); Schakel := EersteSchakel; while Schakel &lt;> nil do with Schakel^ do begin {----- Ouder-omgeving vaststellen -----} if Eigenaar = OuderSegment then begin if not Dos3punt2 then begin if (Functie = 'Env ') then begin Ouder := DitSegment + 1; Pijl := 'Û'; end else Pijl := '&lt;'; end {if not Dos3punt2} else begin if ((Functie = 'Env' + chr (39)) or (Functie = 'Data')) and (Ouder = $0000) then begin Ouder := DitSegment + 1; Pijl := 'Û'; end else Pijl := '&lt;'; end {else: Dos3punt2}; end {with Schakel^}; {----- Keten-weergave -----} writeln (WordHex (DitSegment) , ' ', WordHex (Paragrafen) , ' ', Signatuur , ' ', WordHex (Eigenaar) , ' ', WordHex (Omgeving) , ' ', Functie , ' ', Oorsprong, Pijl , ' ', KorteNaam , ' ', LangeNaam ); {----- Schakel-verloop -----} Schakel := Schakel^.Volgende; end {while Schakel &lt;> nil}; {----- Afsluiting rapportage -----} writeln; write ('* = First command interpreter at '); if ProgGevonden then writeln (WordHex (EersteProg), ':0000') else writeln ('?'); write ('M = Master environment at '); if Meester > $0000 then writeln (WordHex (Meester), ':0000') else writeln ('?'); write ('&lt; = Parent proces at '); writeln (WordHex (OuderSegment), ':0000'); write ('Û = Parent environment at '); if Ouder > $0000 then writeln (WordHex (Ouder), ':0000') else writeln ('?'); writeln ('> = Current proces at ', WordHex (prefixseg), ':0000'); writeln (' returns to ', WordHex (TerugkeerSegment), ':', WordHex (TerugkeerOffset)); END. </code></pre> <p>(Above ASCII 127, there may be some ASCII/ANSI translation issues in this presentation.)</p>
3
2009-07-24T19:45:07Z
[ "python", "windows", "environment-variables" ]
Interface for modifying Windows environment variables from Python
1,085,852
<p>How can I persistently modify the Windows environment variables from a Python script? (it's the setup.py script)</p> <p>I'm looking for a standard function or module to use for this. I'm already familiar with the <a href="http://code.activestate.com/recipes/416087/">registry way of doing it</a>, but any comments regarding that are also welcome.</p>
15
2009-07-06T07:48:40Z
28,439,472
<p>This Python-script[*] attempts to modify the GLOBAL env-vars in registry, if no-permissions falls-back to user's registry, and then notifies all windows about the change:</p> <pre class="lang-py prettyprint-override"><code>""" Show/Modify/Append registry env-vars (ie `PATH`) and notify Windows-applications to pickup changes. First attempts to show/modify HKEY_LOCAL_MACHINE (all users), and if not accessible due to admin-rights missing, fails-back to HKEY_CURRENT_USER. Write and Delete operations do not proceed to user-tree if all-users succeed. Syntax: {prog} : Print all env-vars. {prog} VARNAME : Print value for VARNAME. {prog} VARNAME VALUE : Set VALUE for VARNAME. {prog} +VARNAME VALUE : Append VALUE in VARNAME delimeted with ';' (i.e. used for `PATH`). {prog} -VARNAME : Delete env-var value. Note that the current command-window will not be affected, changes would apply only for new command-windows. """ import winreg import os, sys, win32gui, win32con def reg_key(tree, path, varname): return '%s\%s:%s' % (tree, path, varname) def reg_entry(tree, path, varname, value): return '%s=%s' % (reg_key(tree, path, varname), value) def query_value(key, varname): value, type_id = winreg.QueryValueEx(key, varname) return value def show_all(tree, path, key): i = 0 while True: try: n,v,t = winreg.EnumValue(key, i) print(reg_entry(tree, path, n, v)) i += 1 except OSError: break ## Expected, this is how iteration ends. def notify_windows(action, tree, path, varname, value): win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') print("---%s %s" % (action, reg_entry(tree, path, varname, value))) def manage_registry_env_vars(varname=None, value=None): reg_keys = [ ('HKEY_LOCAL_MACHINE', r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'), ('HKEY_CURRENT_USER', r'Environment'), ] for (tree_name, path) in reg_keys: tree = eval('winreg.%s'%tree_name) try: with winreg.ConnectRegistry(None, tree) as reg: with winreg.OpenKey(reg, path, 0, winreg.KEY_ALL_ACCESS) as key: if not varname: show_all(tree_name, path, key) else: if not value: if varname.startswith('-'): varname = varname[1:] value = query_value(key, varname) winreg.DeleteValue(key, varname) notify_windows("Deleted", tree_name, path, varname, value) break ## Don't propagate into user-tree. else: value = query_value(key, varname) print(reg_entry(tree_name, path, varname, value)) else: if varname.startswith('+'): varname = varname[1:] value = query_value(key, varname) + ';' + value winreg.SetValueEx(key, varname, 0, winreg.REG_EXPAND_SZ, value) notify_windows("Updated", tree_name, path, varname, value) break ## Don't propagate into user-tree. except PermissionError as ex: print("!!!Cannot access %s due to: %s" % (reg_key(tree_name, path, varname), ex)) except FileNotFoundError as ex: print("!!!Cannot find %s due to: %s" % (reg_key(tree_name, path, varname), ex)) if __name__=='__main__': args = sys.argv argc = len(args) if argc &gt; 3: print(__doc__.format(prog=args[0])) sys.exit() manage_registry_env_vars(*args[1:]) </code></pre> <p>Below are some usage examples, assuming it has been saved in a file called <code>setenv.py</code> somewhere in your current path. Note that in these examples i <strong>didn't have admin-rights</strong>, so the changes affected only my local user's registry tree:</p> <pre><code>&gt; REM ## Print all env-vars &gt; setenv.py !!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied HKEY_CURRENT_USER\Environment:PATH=... ... &gt; REM ## Query env-var: &gt; setenv.py PATH C:\foo !!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied !!!Cannot find HKEY_CURRENT_USER\Environment:PATH due to: [WinError 2] The system cannot find the file specified &gt; REM ## Set env-var: &gt; setenv.py PATH C:\foo !!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied ---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo &gt; REM ## Append env-var: &gt; setenv.py +PATH D:\Bar !!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied ---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo;D:\Bar &gt; REM ## Delete env-var: &gt; setenv.py -PATH !!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied ---Deleted HKEY_CURRENT_USER\Environment:PATH </code></pre> <p>[*] Adapted from: <a href="http://code.activestate.com/recipes/416087-persistent-environment-variables-on-windows/" rel="nofollow">http://code.activestate.com/recipes/416087-persistent-environment-variables-on-windows/</a></p>
0
2015-02-10T18:50:23Z
[ "python", "windows", "environment-variables" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
1,085,929
<p>As you've identified, using a JVM doesn't restrict you to using the Java language. A list of JVM languages and links can be found <a href="http://en.wikipedia.org/wiki/List%5Fof%5FJVM%5Flanguages" rel="nofollow">here</a>. <em>However</em>, the Google App Engine does restrict the set of classes you can use from the normal Java SE set, and you will want to investigate if any of these implementations can be used on the app engine.</p> <p>EDIT: I see you've found such a list</p> <p>I can't comment on the performance of Python. However, the JVM is a very powerful platform performance-wise, given its ability to dynamically compile and optimise code during the run time.</p> <p>Ultimately performance will depend on what your application does, and how you code it. In the absence of further info, I think it's not possible to give any more pointers in this area.</p>
6
2009-07-06T08:13:08Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
1,086,259
<p>Based on experience with running these VMs on other platforms, I'd say that you'll probably get more raw performance out of Java than Python. Don't underestimate Python's selling points, however: The Python language is much more productive in terms of lines of code - the general agreement is that Python requires a third of the code of an equivalent Java program, while remaining as or more readable. This benefit is multiplied by the ability to run code immediately without an explicit compile step.</p> <p>With regards to available libraries, you'll find that much of the extensive Python runtime library works out of the box (as does Java's). The popular Django Web framework (<a href="http://www.djangoproject.com/">http://www.djangoproject.com/</a>) is also supported on AppEngine.</p> <p>With regards to 'power', it's difficult to know what you mean, but Python is used in many different domains, especially the Web: YouTube is written in Python, as is Sourceforge (as of last week).</p>
16
2009-07-06T09:48:32Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
1,087,878
<p>I'm biased (being a Python expert but pretty rusty in Java) but I think the Python runtime of GAE is currently more advanced and better developed than the Java runtime -- the former has had one extra year to develop and mature, after all.</p> <p>How things will proceed going forward is of course hard to predict -- demand is probably stronger on the Java side (especially since it's not just about Java, but other languages perched on top of the JVM too, so it's THE way to run e.g. PHP or Ruby code on App Engine); the Python App Engine team however does have the advantage of having on board Guido van Rossum, the inventor of Python and an amazingly strong engineer.</p> <p>In terms of flexibility, the Java engine, as already mentioned, does offer the possibility of running JVM bytecode made by different languages, not just Java -- if you're in a multi-language shop that's a pretty large positive. Vice versa, if you loathe Javascript but must execute some code in the user's browser, Java's GWT (generating the Javascript for you from your Java-level coding) is far richer and more advanced than Python-side alternatives (in practice, if you choose Python, you'll be writing some JS yourself for this purpose, while if you choose Java GWT is a usable alternative if you loathe writing JS).</p> <p>In terms of libraries it's pretty much a wash -- the JVM is restricted enough (no threads, no custom class loaders, no JNI, no relational DB) to hamper the simple reuse of existing Java libraries as much, or more, than existing Python libraries are similarly hampered by the similar restrictions on the Python runtime.</p> <p>In terms of performance, I think it's a wash, though you should benchmark on tasks of your own -- don't rely on the performance of highly optimized JIT-based JVM implementations discounting their large startup times and memory footprints, because the app engine environment is very different (startup costs will be paid often, as instances of your app are started, stopped, moved to different hosts, etc, all trasparently to you -- such events are typically much cheaper with Python runtime environments than with JVMs).</p> <p>The XPath/XSLT situation (to be euphemistic...) is not exactly perfect on either side, sigh, though I think it may be a tad less bad in the JVM (where, apparently, substantial subsets of Saxon can be made to run, with some care). I think it's worth opening issues on the <a href="http://code.google.com/p/googleappengine/issues/list">Appengine Issues</a> page with XPath and XSLT in their titles -- right now there are only issues asking for specific libraries, and that's myopic: I don't really care HOW a good XPath/XSLT is implemented, for Python and/or for Java, as long as I get to use it. (Specific libraries may ease migration of existing code, but that's less important than being able to perform such tasks as "rapidly apply XSLT transformation" in SOME way!-). I know I'd star such an issue if well phrased (especially in a language-independent way).</p> <p>Last but not least: remember that you can have different version of your app (using the same datastore) some of which are implemented with the Python runtime, some with the Java runtime, and you can access versions that differ from the "default/active" one with explicit URLs. So you could have both Python <em>and</em> Java code (in different versions of your app) use and modify the same data store, granting you even more flexibility (though only one will have the "nice" URL such as foobar.appspot.com -- which is probably important only for access by interactive users on browsers, I imagine;-).</p>
113
2009-07-06T16:17:10Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
1,093,160
<p>I'm strongly recommending Java for GAE and here's why:</p> <ol> <li>Performance: Java is potentially faster then Python.</li> <li>Python development is under pressure of a lack of third-party libraries. For example, there is no XSLT for Python/GAE at all. Almost all Python libraries are C bindings (and those are unsupported by GAE).</li> <li>Memcache API: Java SDK have more interesting abilities than Python SDK.</li> <li>Datastore API: JDO is very slow, but native Java datastore API is very fast and easy.</li> </ol> <p>I'm using Java/GAE in development right now.</p>
5
2009-07-07T15:50:45Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
1,337,632
<p>There's also project <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan" rel="nofollow">Unladen Swallow</a>, which is apparently Google-funded if not Google-owned. They're trying to implement a LLVM-based backend for Python 2.6.1 bytecode, so they can use a JIT and various nice native code/GC/multi-core optimisations. (Nice quote: "We aspire to do no original work, instead using as much of the last 30 years of research as possible.") They're looking for a 5x speed-up to CPython.</p> <p>Of course this doesn't answer your immediate question, but points towards a "closing of the gap" (if any) in the future (hopefully).</p>
2
2009-08-26T21:36:11Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
1,442,628
<p>Gone with Python even though GWT seems a perfect match for the kind of an app I'm developing. JPA is pretty messed up on GAE (e.g. no @Embeddable and other obscure non-documented limitations). Having spent a week, I can tell that Java just doesn't feel right on GAE at the moment.</p>
1
2009-09-18T04:40:43Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
1,464,516
<p>Watch this app for changes in Python and Java performance:</p> <p><a href="http://gaejava.appspot.com/">http://gaejava.appspot.com/</a></p> <p>Currently, Python and using the low-level API in Java are faster than JDO on Java, <strong>for this simple test</strong>. At least if the underlying engine changes, that app should reflect performance changes.</p>
66
2009-09-23T07:45:21Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
2,636,174
<p>The beauty of python nowdays is how well it communicates with other languages. For instance you can have both python and java on the same table with Jython. Of course jython even though it fully supports java libraries it does not support fully python libraries. But its an ideal solution if you want to mess with Java Libraries. It even allows you to mix it with Java code with no extra coding. </p> <p>But even python itself has made some steps forwared. See ctypes for example, near C speed , direct accees to C libraries all of this without leaving the comfort of python coding. Cython goes one step further , allowing to mix c code with python code with ease, or even if you dont want to mess with c or c++ , you can still code in python but use statically type variables making your python programms as fast as C apps. Cython is both used and supported by google by the way. </p> <p>Yesterday I even found tools for python to inline C or even Assembly (see CorePy) , you cant get any more powerful than that. </p> <p>Python is surely a very mature language, not only standing on itself , but able to coooperate with any other language with easy. I think that is what makes python an ideal solution even in a very advanced and demanding scenarios.</p> <p>With python you can have acess to C/C++ ,Java , .NET and many other libraries with almost zero additional coding giving you also a language that minimises, simplifies and beautifies coding. Its a very tempting language. </p>
2
2010-04-14T09:14:37Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
2,638,859
<p>An important question to consider in deciding between Python and Java is <strong>how you will use the datastore in each language</strong> (and most other angles to the original question have already been covered quite well in this topic).</p> <p><strong>For Java</strong>, the standard method is to use JDO or JPA. These are great for portability but are not very well suited to the datastore.</p> <p>A low-level API is available but this is too low level for day-to-day use - it is more suitable for building 3rd party libraries.</p> <p><strong>For Python</strong> there is an API designed specifically to provide applications with easy but powerful access to the datastore. It is great except that it is not portable so it locks you into GAE.</p> <p>Fortunately, there are solutions being developed for the weaknesses listed for both languages.</p> <p><strong>For Java</strong>, the low-level API is being used to develop persistence libraries that are much better suited to the datastore then JDO/JPA (IMO). Examples include the <a href="https://github.com/siena/siena" rel="nofollow">Siena project</a>, and <a href="https://code.google.com/p/objectify-appengine/" rel="nofollow">Objectify</a>. </p> <p>I've recently started using Objectify and am finding it to be very easy to use and well suited to the datastore, and its growing popularity has translated into good support. For example, Objectify is officially supported by Google's new Cloud Endpoints service. On the other hand, Objectify only works with the datastore, while Siena is 'inspired' by the datastore but is designed to work with a variety of both SQL databases and NoSQL datastores.</p> <p><strong>For Python</strong>, there are efforts being made to allow the use of the Python GAE datastore API off of the GAE. One example is the SQLite backend that Google released for use with the SDK, but I doubt they intend this to grow into something production ready. The <a href="http://code.google.com/p/typhoonae/" rel="nofollow">TyphoonAE</a> project probably has more potential, but I don't think it is production ready yet either (correct me if I am wrong).</p> <p>If anyone has experience with any of these alternatives or knows of others, please add them in a comment. Personally, I really like the GAE datastore - I find it to be a considerable improvement over the AWS SimpleDB - so I wish for the success of these efforts to alleviate some of the issues in using it.</p>
9
2010-04-14T15:44:29Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
2,680,204
<p>It's a good question, and I think many of the responses have given good view points of pros and cons on both sides of the fence. I've tried both Python and JVM-based AppEngine (in my case I was using <a href="http://gaelyk.appspot.com/" rel="nofollow">Gaelyk</a> which is a Groovy application framework built for AppEngine). When it comes to performance on the platform, one thing I hadn't considered until it was staring me in the face is the implication of "Loading Requests" that occur on the Java side of the fence. When using Groovy these loading requests are a killer.</p> <p>I put a post together on the topic (<a href="http://distractable.net/coding/google-appengine-java-vs-python-performance-comparison/" rel="nofollow">http://distractable.net/coding/google-appengine-java-vs-python-performance-comparison/</a>) and I'm hoping to find a way of working around the problem, but if not I think I'll be going back to a Python + Django combination until cold starting java requests has less of an impact.</p>
3
2010-04-21T03:54:05Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
2,979,149
<p>Based on how much I hear Java people complain about AppEngine compared to Python users, I would say Python is much less stressful to use.</p>
3
2010-06-05T04:24:36Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
3,393,601
<p>I've been amazed at how clean, straightforward, and problem free the Python/Django SDK is. However I started running into situations where I needed to start doing more JavaScript and thought I might want to take advantage of the GWT and other Java utilities. I've gotten just half way through the GAE Java tutorial, and have had one problem after another: Eclipse configuration issues, JRE versionitis, the mind-numbing complexity of Java, and a confusing and possibly broken tutorial. Checking out this site and others linked from here clinched it for me. I'm going back to Python, and I'll look into Pyjamas to help with my JavaScript challenges.</p>
6
2010-08-03T04:37:36Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
5,096,947
<p>One think to take into account are the frameworks you intend yo use. Not all frameworks on Java side are well suited for applications running on App Engine, which is somewhat different than traditional Java app servers. </p> <p>One thing to consider is the application startup time. With traditional Java web apps you don't really need to think about this. The application starts and then it just runs. Doesn't really matter if the startup takes 5 seconds or couple of minutes. With App Engine you might end up in a situation where the application is only started when a request comes in. This means the user is waiting while your application boots up. New GAE features like reserved instances help here, but check first.</p> <p>Another thing are the different limitations GAE psoes on Java. Not all frameworks are happy with the limitations on what classes you can use or the fact that threads are not allowed or that you can't access local filesystem. These issues are probably easy to find out by just googling about GAE compatibility.</p> <p>I've also seen some people complaining about issues with session size on modern UI frameworks (Wicket, namely). In general these frameworks tend to do certain trade-offs in order to make development fun, fast and easy. Sometimes this may lead to conflicts with the App Engine limitations. </p> <p>I initially started developing working on GAE with Java, but then switched to Python because of these reasons. My <em>personal feeling</em> is that Python is a better choice for App Engine development. I think Java is more "at home" for example on Amazon's Elastic Beanstalk.</p> <p><strong>BUT</strong> with App Engine things are changing very rapidly. GAE is changing itself and as it becomes more popular, the frameworks are also changing to work around its limitations. </p>
1
2011-02-23T20:51:34Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
18,255,495
<p><strong>June 2013:</strong> This video is a very good answer by a google engineer:</p> <p><a href="http://www.youtube.com/watch?v=tLriM2krw2E">http://www.youtube.com/watch?v=tLriM2krw2E</a></p> <p>TLDR; is: </p> <ul> <li>Pick the language that you and your team is most productive with</li> <li>If you want to build something for production: Java or Python (not Go)</li> <li>If you have a big team and a complex code base: Java (because of static code analysis and refactoring)</li> <li>Small teams that iterate quickly: Python (although Java is also okay)</li> </ul>
11
2013-08-15T15:00:01Z
[ "java", "python", "google-app-engine" ]
Choosing Java vs Python on Google App Engine
1,085,898
<p>Currently Google App Engine supports both Python &amp; Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!</p> <p><strong>Edit:</strong> <a href="http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1">http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1</a></p> <p><strong>Edit:</strong> By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.</p>
147
2009-07-06T08:05:58Z
25,894,549
<p>I'm a little late to the conversation, but here are my two cents. I really had a hard time choosing between Python and Java, since I am well versed in both languages. As we all know, there are advantages and disadvantages for both, and you have to take in account your requirements and the frameworks that work best for your project. </p> <p>As I usually do in this type of dilemmas, I look for numbers to support my decision. I decided to go with Python for many reasons, but in my case, there was one plot that was the tipping point. If you search "Google App Engine" in GitHub as of <strong>September 2014</strong>, you will find the following figure:</p> <p><img src="http://i.stack.imgur.com/z4M8C.png" alt="GAE Language Stats"></p> <p>There could be many biases in these numbers, but overall, there are three times more GAE Python repositories than GAE Java repositories. Not only that, but if you list the projects by the "number of stars" you will see that a majority of the Python projects appear at the top (you have to take in account that Python has been around longer). To me, this makes a strong case for Python because I take in account community adoption &amp; support, documentation, and availability of open-source projects.</p>
5
2014-09-17T15:24:57Z
[ "java", "python", "google-app-engine" ]
where to start OpenID implementation in python,which API is better suits
1,086,127
<p>im using python API in our research project.i read lot of ppt and material, and finally understand this concept now i have task to execute simple function which is chek user credential thorough openid provider and return successful after the valid user check.....</p>
-1
2009-07-06T09:07:45Z
1,086,150
<p>Why not use <a href="http://openidenabled.com/python-openid/" rel="nofollow">Python OpenID</a> library?</p>
2
2009-07-06T09:13:27Z
[ "python" ]
where to start OpenID implementation in python,which API is better suits
1,086,127
<p>im using python API in our research project.i read lot of ppt and material, and finally understand this concept now i have task to execute simple function which is chek user credential thorough openid provider and return successful after the valid user check.....</p>
-1
2009-07-06T09:07:45Z
1,086,227
<p>To add to the recommendation of the Python OpenID library: their docs pages for the <a href="http://openidenabled.com/files/python-openid/docs/2.2.4/openid.server.server-module.html" rel="nofollow">server</a> and <a href="http://openidenabled.com/files/python-openid/docs/2.2.4/openid.consumer.consumer-module.html" rel="nofollow">consumer</a> modules both have useful Overview sections which you should read as a good starting point. The <a href="http://openidenabled.com/files/python-openid/repos/2.x.x/examples/" rel="nofollow">examples directory</a> is also useful; I've written things starting from <code>server.py</code> and <code>consumer.py</code> from there.</p>
3
2009-07-06T09:37:20Z
[ "python" ]
Is is possible to return an object or value from a Python script to the hosting application?
1,086,188
<p>For example in Lua you can place the following line at the end of a script:</p> <pre><code>return &lt;some-value/object&gt; </code></pre> <p>The value/object that is returned can then be retrieved by the hosting application.</p> <p>I use this pattern so that scripts can represent factories for event handlers. The script-based event handlers are then used to extend the application. For example the hosting application runs a script called 'SomeEventHandler.lua' which defines and returns an object that is an event handler for 'SomeEvent' in your application.</p> <p>Can this be done in Python? Or is there a better way to achieve this?</p> <p>More specifically I am embedding IronPython in my C# application and am looking for a way to instance these script-based event handlers which will allow the application to be extended using Python.</p>
2
2009-07-06T09:23:41Z
1,086,209
<p>It's totally possible and a common technique when embedding Python. <a href="http://www.linuxjournal.com/article/8497" rel="nofollow">This article</a> shows the basics, as does <a href="http://python.active-venture.com/ext/pure-embedding.html" rel="nofollow">this page</a>. The core function is <code>PyObject_CallObject()</code> which calls code written in Python, from C.</p>
2
2009-07-06T09:29:59Z
[ "c#", "python", "ironpython" ]
Is is possible to return an object or value from a Python script to the hosting application?
1,086,188
<p>For example in Lua you can place the following line at the end of a script:</p> <pre><code>return &lt;some-value/object&gt; </code></pre> <p>The value/object that is returned can then be retrieved by the hosting application.</p> <p>I use this pattern so that scripts can represent factories for event handlers. The script-based event handlers are then used to extend the application. For example the hosting application runs a script called 'SomeEventHandler.lua' which defines and returns an object that is an event handler for 'SomeEvent' in your application.</p> <p>Can this be done in Python? Or is there a better way to achieve this?</p> <p>More specifically I am embedding IronPython in my C# application and am looking for a way to instance these script-based event handlers which will allow the application to be extended using Python.</p>
2
2009-07-06T09:23:41Z
1,086,213
<p>This can be done in Python just the same way. You can require the plugin to provide a getHandler() function / method that returns the event handler:</p> <pre><code>class myPlugin(object): def doIt(self,event,*args): print "Doing important stuff" def getHandler(self,document): print "Initializing plugin" self._doc = document return doIt </code></pre> <p>When the user says "I want to use plugin X now," you know which function to call. If the plugin is not only to be called after a direct command, but also on certain events (like e.g. loading a graphics element), you can also provide the plugin author with possibilities to bind the handler to this very event.</p>
3
2009-07-06T09:30:59Z
[ "c#", "python", "ironpython" ]
Is is possible to return an object or value from a Python script to the hosting application?
1,086,188
<p>For example in Lua you can place the following line at the end of a script:</p> <pre><code>return &lt;some-value/object&gt; </code></pre> <p>The value/object that is returned can then be retrieved by the hosting application.</p> <p>I use this pattern so that scripts can represent factories for event handlers. The script-based event handlers are then used to extend the application. For example the hosting application runs a script called 'SomeEventHandler.lua' which defines and returns an object that is an event handler for 'SomeEvent' in your application.</p> <p>Can this be done in Python? Or is there a better way to achieve this?</p> <p>More specifically I am embedding IronPython in my C# application and am looking for a way to instance these script-based event handlers which will allow the application to be extended using Python.</p>
2
2009-07-06T09:23:41Z
1,086,219
<p>The way I would do it (and the way I've seen it done) is have a function for each event all packed into one module (or across several, doesn't matter), and then call the function through C/C++/C# and use its return value.</p>
1
2009-07-06T09:33:27Z
[ "c#", "python", "ironpython" ]
Is is possible to return an object or value from a Python script to the hosting application?
1,086,188
<p>For example in Lua you can place the following line at the end of a script:</p> <pre><code>return &lt;some-value/object&gt; </code></pre> <p>The value/object that is returned can then be retrieved by the hosting application.</p> <p>I use this pattern so that scripts can represent factories for event handlers. The script-based event handlers are then used to extend the application. For example the hosting application runs a script called 'SomeEventHandler.lua' which defines and returns an object that is an event handler for 'SomeEvent' in your application.</p> <p>Can this be done in Python? Or is there a better way to achieve this?</p> <p>More specifically I am embedding IronPython in my C# application and am looking for a way to instance these script-based event handlers which will allow the application to be extended using Python.</p>
2
2009-07-06T09:23:41Z
1,086,244
<p>See some examples in <a href="http://www.voidspace.org.uk/ironpython/hosting%5Fapi.shtml" rel="nofollow">Embedding the Dynamic Language Runtime</a>.</p> <p>A simple example, <a href="http://www.voidspace.org.uk/ironpython/hosting%5Fapi.shtml#setting-and-fetching-variables" rel="nofollow">setting-and-fetching-variables</a>:</p> <pre><code>SourceCodeKind st = SourceCodeKind.Statements; string source = "print 'Hello World'"; script = eng.CreateScriptSourceFromString(source, st); scope = eng.CreateScope(); script.Execute(scope); // The namespace holds the variables that the code creates in the process of executing it. int value = 3; scope.SetVariable("name", value); script.Execute(scope); int result = scope.GetVariable&lt;int&gt;("name"); </code></pre>
2
2009-07-06T09:45:15Z
[ "c#", "python", "ironpython" ]
Parsing HTML rows into CSV
1,086,266
<p>First off the html row looks like this: </p> <pre><code>&lt;tr class="evenColor"&gt; blahblah TheTextIneed blahblah and ends with &lt;/tr&gt; </code></pre> <p>I would show the real html but I am sorry to say don't know how to block it. <em>feels shame</em></p> <p>Using BeautifulSoup (Python) or any other recommended Screen Scraping/Parsing method I would like to output about 1200 .htm files in the same directory into a CSV format. This will eventually go into an SQL database. Each directory represents a year and I plan to do at least 5 years.</p> <p>I have been goofing around with <code>glob</code> as the best way to do this from some advice. This is what I have so far and am stuck.</p> <pre><code>import glob from BeautifulSoup import BeautifulSoup for filename in glob.glob('/home/phi/data/NHL/pl0708/pl02*.htm'): #these files go from pl020001.htm to pl021230.htm sequentially soup = BeautifulSoup(open(filename["r"])) for row in soup.findAll("tr", attrs={ "class" : "evenColor" }) </code></pre> <p>I realize this is ugly but it's my first time attempting anything like this. This one problem has taken me months to get to this point after realizing that I don't have to manually go through thousands of files copy and pasting into excel. I have also realized that I can kick my computer repeatedly out of frustration and it still works (not recommended). I am getting close and I need to know what to do next to make those CSV files. Please help or my monitor finally gets hammer punched.</p>
1
2009-07-06T09:50:25Z
1,086,311
<p>That looks fine, and BeautifulSoup is useful for this (although I personally tend to use lxml). You should be able to take that data you get, and make a csv file out of is using the csv module without any obvious problems...</p> <p>I think you need to actually tell us what the problem is. "It still doesn't work" is not a problem descripton.</p>
2
2009-07-06T10:02:33Z
[ "python", "html", "csv", "screen-scraping", "beautifulsoup" ]
Parsing HTML rows into CSV
1,086,266
<p>First off the html row looks like this: </p> <pre><code>&lt;tr class="evenColor"&gt; blahblah TheTextIneed blahblah and ends with &lt;/tr&gt; </code></pre> <p>I would show the real html but I am sorry to say don't know how to block it. <em>feels shame</em></p> <p>Using BeautifulSoup (Python) or any other recommended Screen Scraping/Parsing method I would like to output about 1200 .htm files in the same directory into a CSV format. This will eventually go into an SQL database. Each directory represents a year and I plan to do at least 5 years.</p> <p>I have been goofing around with <code>glob</code> as the best way to do this from some advice. This is what I have so far and am stuck.</p> <pre><code>import glob from BeautifulSoup import BeautifulSoup for filename in glob.glob('/home/phi/data/NHL/pl0708/pl02*.htm'): #these files go from pl020001.htm to pl021230.htm sequentially soup = BeautifulSoup(open(filename["r"])) for row in soup.findAll("tr", attrs={ "class" : "evenColor" }) </code></pre> <p>I realize this is ugly but it's my first time attempting anything like this. This one problem has taken me months to get to this point after realizing that I don't have to manually go through thousands of files copy and pasting into excel. I have also realized that I can kick my computer repeatedly out of frustration and it still works (not recommended). I am getting close and I need to know what to do next to make those CSV files. Please help or my monitor finally gets hammer punched.</p>
1
2009-07-06T09:50:25Z
1,086,317
<p>You don't really explain why you are stuck - what's not working exactly?</p> <p>The following line may well be your problem:</p> <pre><code>soup = BeautifulSoup(open(filename["r"])) </code></pre> <p>It looks to me like this should be:</p> <pre><code>soup = BeautifulSoup(open(filename, "r")) </code></pre> <p>The following line:</p> <pre><code>for row in soup.findAll("tr", attrs={ "class" : "evenColor" }) </code></pre> <p>looks like it will only pick out even rows (assuming your even rows have the class 'evenColor' and odd rows have 'oddColor'). Assuming you want all rows with a class of either evenColor or oddColor, you can use a regular expression to match the class value:</p> <pre><code>for row in soup.findAll("tr", attrs={ "class" : re.compile(r"evenColor|oddColor") }) </code></pre>
4
2009-07-06T10:06:04Z
[ "python", "html", "csv", "screen-scraping", "beautifulsoup" ]
Parsing HTML rows into CSV
1,086,266
<p>First off the html row looks like this: </p> <pre><code>&lt;tr class="evenColor"&gt; blahblah TheTextIneed blahblah and ends with &lt;/tr&gt; </code></pre> <p>I would show the real html but I am sorry to say don't know how to block it. <em>feels shame</em></p> <p>Using BeautifulSoup (Python) or any other recommended Screen Scraping/Parsing method I would like to output about 1200 .htm files in the same directory into a CSV format. This will eventually go into an SQL database. Each directory represents a year and I plan to do at least 5 years.</p> <p>I have been goofing around with <code>glob</code> as the best way to do this from some advice. This is what I have so far and am stuck.</p> <pre><code>import glob from BeautifulSoup import BeautifulSoup for filename in glob.glob('/home/phi/data/NHL/pl0708/pl02*.htm'): #these files go from pl020001.htm to pl021230.htm sequentially soup = BeautifulSoup(open(filename["r"])) for row in soup.findAll("tr", attrs={ "class" : "evenColor" }) </code></pre> <p>I realize this is ugly but it's my first time attempting anything like this. This one problem has taken me months to get to this point after realizing that I don't have to manually go through thousands of files copy and pasting into excel. I have also realized that I can kick my computer repeatedly out of frustration and it still works (not recommended). I am getting close and I need to know what to do next to make those CSV files. Please help or my monitor finally gets hammer punched.</p>
1
2009-07-06T09:50:25Z
1,086,496
<p>You need to import the <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a> by adding <code>import csv</code> to the top of your file.</p> <p>Then you'll need something to create a csv file outside your loop of the rows, like so:</p> <pre><code>writer = csv.writer(open("%s.csv" % filename, "wb")) </code></pre> <p>Then you need to actually pull the data out of the html row in your loop, similar to</p> <pre><code>values = (td.fetchText() for td in row) writer.writerow(values) </code></pre>
4
2009-07-06T11:17:50Z
[ "python", "html", "csv", "screen-scraping", "beautifulsoup" ]
Django: information captured from URLs available in template files?
1,086,531
<p>Given:</p> <pre><code>urlpatterns = \ patterns('blog.views', (r'^blog/(?P&lt;year&gt;\d{4})/$', 'year_archive', {'foo': 'bar'}), ) </code></pre> <p>in a urls.py file. (Should it be 'archive_year' instead of 'year_archive' ? - see below for ref.)</p> <p>Is it possible to capture information from the URL matching (the value of "year" in this case) for use in the optional dictionary?. E.g.: the value of year instead 'bar'?</p> <p>Replacing 'bar' with year results in: "NameError ... name 'year' is not defined".</p> <p>The above is just an example; I know that year is available in the template HTML file for archive_year, but this is not the case for archive_month. And there could be custom information represented in the URL that is needed in a template HTML file.</p> <p>(The example is from page "URL dispatcher", section "Passing extra options to view functions", <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/http/urls/</a>, in the Django documentation.)</p>
1
2009-07-06T11:33:25Z
1,086,558
<p>No, that's not possible within the URLConf -- the dispatcher has a fixed set of things it does. (It takes the group dictionary from your regex match and passes it as keyword arguments to your view function.) Within your (custom) view function, you should be able to manipulate how those values are passed into the template context.</p> <p>Writing a custom view to map year to "foo" given this URLConf would be something like:</p> <pre><code>def custom_view(request, year, foo): context = RequestContext(request, {'foo': year}) return render_to_response('my_template.tmpl', context) </code></pre> <p>The reason that you get a <code>NameError</code> in the case you're describing is because Python is looking for an identifier called <code>year</code> in the surrounding scope and it doesn't exist there -- it's only a substring in the regex pattern.</p>
4
2009-07-06T11:42:37Z
[ "python", "django" ]
How to use QTP to test the application which operates in citrix of Remote Machine?
1,086,758
<p>When i tried recording using QTP, every thing goes well till the application sign in. i.e it gets upto the user Id and password entry, But QTP fails to recognise afterthat. Is there any way to handle this?</p> <p>Application is to be invoked using Citirx, in VPN.</p>
1
2009-07-06T12:40:15Z
1,121,154
<p>QTP performs GUI recognition and interaction through Windows Handle. So it has to be running <strong><em>under</em></strong> Citrix (i.e. installed on the same virtual machine as your Application Under Test). </p> <p>If you have the above, make sure Screen Resolution, Windows Theme, Font size, and other global GUI settings are the same.</p>
0
2009-07-13T18:13:49Z
[ "c#", "python", "ruby" ]
Can I be warned when I used a generator function by accident
1,087,019
<p>I was working with generator functions and private functions of a class. I am wondering</p> <ol> <li>Why when yielding (which in my one case was by accident) in __someFunc that this function just appears not to be called from within __someGenerator. Also what is the terminology I want to use when referring to these aspects of the language?</li> <li>Can the python interpreter warn of such instances? </li> </ol> <p>Below is an example snippet of my scenario.</p> <pre><code>class someClass(): def __init__(self): pass #Copy and paste mistake where yield ended up in a regular function def __someFunc(self): print "hello" #yield True #if yielding in this function it isn't called def __someGenerator (self): for i in range(0, 10): self.__someFunc() yield True yield False def someMethod(self): func = self.__someGenerator() while func.next(): print "next" sc = someClass() sc.someMethod() </code></pre> <p>I got burned on this and spent some time trying to figure out why a function just wasn't getting called. I finally discovered I was yielding in function I didn't want to in.</p>
2
2009-07-06T13:38:09Z
1,087,048
<p>A "generator" isn't so much a language feature, as a name for functions that "yield." Yielding is pretty much always legal. There's not really any way for Python to know that you didn't "mean" to yield from some function.</p> <p>This PEP <a href="http://www.python.org/dev/peps/pep-0255/">http://www.python.org/dev/peps/pep-0255/</a> talks about generators, and may help you understand the background better. </p> <p>I sympathize with your experience, but compilers can't figure out what you "meant for them to do", only what you actually told them to do.</p>
6
2009-07-06T13:43:41Z
[ "python", "function", "generator", "language-features" ]
Can I be warned when I used a generator function by accident
1,087,019
<p>I was working with generator functions and private functions of a class. I am wondering</p> <ol> <li>Why when yielding (which in my one case was by accident) in __someFunc that this function just appears not to be called from within __someGenerator. Also what is the terminology I want to use when referring to these aspects of the language?</li> <li>Can the python interpreter warn of such instances? </li> </ol> <p>Below is an example snippet of my scenario.</p> <pre><code>class someClass(): def __init__(self): pass #Copy and paste mistake where yield ended up in a regular function def __someFunc(self): print "hello" #yield True #if yielding in this function it isn't called def __someGenerator (self): for i in range(0, 10): self.__someFunc() yield True yield False def someMethod(self): func = self.__someGenerator() while func.next(): print "next" sc = someClass() sc.someMethod() </code></pre> <p>I got burned on this and spent some time trying to figure out why a function just wasn't getting called. I finally discovered I was yielding in function I didn't want to in.</p>
2
2009-07-06T13:38:09Z
1,087,150
<p>Because the <code>return</code> keyword is applicable in both generator functions and regular functions, there's nothing you could possibly check (as @Christopher mentions). The <code>return</code> keyword in a generator indicates that a StopIteration exception should be raised.</p> <p>If you try to <code>return</code> with a value from within a generator (which doesn't make sense, since <code>return</code> just means "stop iteration"), the compiler will complain at compile-time -- this may catch some copy-and-paste mistakes:</p> <pre><code>&gt;&gt;&gt; def foo(): ... yield 12 ... return 15 ... File "&lt;stdin&gt;", line 3 SyntaxError: 'return' with argument inside generator </code></pre> <p>I personally just advise against copy and paste programming. :-)</p> <p>From the PEP:</p> <blockquote> <p>Note that return means "I'm done, and have nothing interesting to return", for both generator functions and non-generator functions.</p> </blockquote>
1
2009-07-06T14:02:40Z
[ "python", "function", "generator", "language-features" ]
Can I be warned when I used a generator function by accident
1,087,019
<p>I was working with generator functions and private functions of a class. I am wondering</p> <ol> <li>Why when yielding (which in my one case was by accident) in __someFunc that this function just appears not to be called from within __someGenerator. Also what is the terminology I want to use when referring to these aspects of the language?</li> <li>Can the python interpreter warn of such instances? </li> </ol> <p>Below is an example snippet of my scenario.</p> <pre><code>class someClass(): def __init__(self): pass #Copy and paste mistake where yield ended up in a regular function def __someFunc(self): print "hello" #yield True #if yielding in this function it isn't called def __someGenerator (self): for i in range(0, 10): self.__someFunc() yield True yield False def someMethod(self): func = self.__someGenerator() while func.next(): print "next" sc = someClass() sc.someMethod() </code></pre> <p>I got burned on this and spent some time trying to figure out why a function just wasn't getting called. I finally discovered I was yielding in function I didn't want to in.</p>
2
2009-07-06T13:38:09Z
1,087,249
<p>I'll try to answer the first of your questions.</p> <p>A regular function, when called like this:</p> <pre><code>val = func() </code></pre> <p>executes its inside statements until it ends or a <code>return</code> statement is reached. Then the return value of the function is assigned to <code>val</code>.</p> <p>If a compiler recognizes the function to actually be a generator and not a regular function (it does that by looking for <code>yield</code> statements inside the function -- if there's at least one, it's a generator), the scenario when calling it the same way as above has different consequences. Upon calling <code>func()</code>, <em>no code inside the function is executed</em>, and a special <code>&lt;generator&gt;</code> value is assigned to <code>val</code>. Then, the first time you call <code>val.next()</code>, the actual statements of <code>func</code> are being executed until a <code>yield</code> or <code>return</code> is encountered, upon which the execution of the function stops, value yielded is returned and generator waits for another call to <code>val.next()</code>.</p> <p>That's why, in your example, function <code>__someFunc</code> didn't print "hello" -- its statements were not executed, because you haven't called <code>self.__someFunc().next()</code>, but only <code>self.__someFunc()</code>.</p> <p>Unfortunately, I'm pretty sure there's no built-in warning mechanism for programming errors like yours.</p>
2
2009-07-06T14:21:41Z
[ "python", "function", "generator", "language-features" ]
Can I be warned when I used a generator function by accident
1,087,019
<p>I was working with generator functions and private functions of a class. I am wondering</p> <ol> <li>Why when yielding (which in my one case was by accident) in __someFunc that this function just appears not to be called from within __someGenerator. Also what is the terminology I want to use when referring to these aspects of the language?</li> <li>Can the python interpreter warn of such instances? </li> </ol> <p>Below is an example snippet of my scenario.</p> <pre><code>class someClass(): def __init__(self): pass #Copy and paste mistake where yield ended up in a regular function def __someFunc(self): print "hello" #yield True #if yielding in this function it isn't called def __someGenerator (self): for i in range(0, 10): self.__someFunc() yield True yield False def someMethod(self): func = self.__someGenerator() while func.next(): print "next" sc = someClass() sc.someMethod() </code></pre> <p>I got burned on this and spent some time trying to figure out why a function just wasn't getting called. I finally discovered I was yielding in function I didn't want to in.</p>
2
2009-07-06T13:38:09Z
1,087,327
<p>Python doesn't know whether you want to create a generator object for later iteration or call a function. But python isn't your only tool for seeing what's going on with your code. If you're using an editor or IDE that allows customized syntax highlighting, you can tell it to give the yield keyword a different color, or even a bright background, which will help you find your errors more quickly, at least. In vim, for example, you might do:</p> <pre><code>:syntax keyword Yield yield :highlight yield ctermbg=yellow guibg=yellow ctermfg=blue guifg=blue </code></pre> <p>Those are horrendous colors, by the way. I recommend picking something better. Another option, if your editor or IDE won't cooperate, is to set up a custom rule in a code checker like pylint. An example from pylint's source tarball: </p> <pre><code>from pylint.interfaces import IRawChecker from pylint.checkers import BaseChecker class MyRawChecker(BaseChecker): """check for line continuations with '\' instead of using triple quoted string or parenthesis """ __implements__ = IRawChecker name = 'custom_raw' msgs = {'W9901': ('use \\ for line continuation', ('Used when a \\ is used for a line continuation instead' ' of using triple quoted string or parenthesis.')), } options = () def process_module(self, stream): """process a module the module's content is accessible via the stream object """ for (lineno, line) in enumerate(stream): if line.rstrip().endswith('\\'): self.add_message('W9901', line=lineno) def register(linter): """required method to auto register this checker""" linter.register_checker(MyRawChecker(linter)) </code></pre> <p>The pylint manual is available here: <a href="http://www.logilab.org/card/pylint_manual" rel="nofollow">http://www.logilab.org/card/pylint_manual</a> And vim's syntax documentation is here: <a href="http://www.vim.org/htmldoc/syntax.html" rel="nofollow">http://www.vim.org/htmldoc/syntax.html</a></p>
2
2009-07-06T14:37:16Z
[ "python", "function", "generator", "language-features" ]
Can I be warned when I used a generator function by accident
1,087,019
<p>I was working with generator functions and private functions of a class. I am wondering</p> <ol> <li>Why when yielding (which in my one case was by accident) in __someFunc that this function just appears not to be called from within __someGenerator. Also what is the terminology I want to use when referring to these aspects of the language?</li> <li>Can the python interpreter warn of such instances? </li> </ol> <p>Below is an example snippet of my scenario.</p> <pre><code>class someClass(): def __init__(self): pass #Copy and paste mistake where yield ended up in a regular function def __someFunc(self): print "hello" #yield True #if yielding in this function it isn't called def __someGenerator (self): for i in range(0, 10): self.__someFunc() yield True yield False def someMethod(self): func = self.__someGenerator() while func.next(): print "next" sc = someClass() sc.someMethod() </code></pre> <p>I got burned on this and spent some time trying to figure out why a function just wasn't getting called. I finally discovered I was yielding in function I didn't want to in.</p>
2
2009-07-06T13:38:09Z
1,087,399
<p>We do this.</p> <p>Generators have names with "generate" or "gen" in their name. It will have a yield statement in the body. Pretty easy to check visually, since no method is much over 20 lines of code.</p> <p>Other methods don't have "gen" in their name.</p> <p>Also, we do not every use <code>__</code> (double underscore) names under any circumstances. 32,000 lines of code. Non <code>__</code> names. </p> <p>The "generator vs. non-generator" method function is entirely a design question. What did the programmer "intend" to happen. The compiler can't easily validate your intent, it can only validate what you actually typed.</p>
0
2009-07-06T14:50:16Z
[ "python", "function", "generator", "language-features" ]
Finding a python process running on Windows with TaskManager
1,087,087
<p>I have several python.exe processes running on my Vista machine and I would like to kill one process thanks to the Windows task manager. What is the best way to find which process to be killed. I've added the 'command line' column on task manager. It can help but not in all cases. is there a better way?</p>
0
2009-07-06T13:49:51Z
1,087,132
<p>Please consider replace Task Manager with the more powerful <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow">Process Explorer</a> here is a demo:<img src="http://i41.tinypic.com/2i6oozp.jpg" alt="alt text" /></p>
1
2009-07-06T13:59:14Z
[ "python", "windows", "taskmanager" ]
Finding a python process running on Windows with TaskManager
1,087,087
<p>I have several python.exe processes running on my Vista machine and I would like to kill one process thanks to the Windows task manager. What is the best way to find which process to be killed. I've added the 'command line' column on task manager. It can help but not in all cases. is there a better way?</p>
0
2009-07-06T13:49:51Z
38,227,531
<p>When I right clicked python in task manager and clicked open file location (win 10) it opened the plex installation folder so for me it is Plex that uses Python.exe to slow my computer down, shame as I use plex all the time for my Roku. Just have to put up with a slow computer and get another one.</p>
0
2016-07-06T15:13:39Z
[ "python", "windows", "taskmanager" ]
Boolean value of objects in Python
1,087,135
<p>As we know, Python has boolean values for objects: If a class has a <code>__len__</code> method, every instance of it for which <code>__len__()</code> happens to return 0 will be evaluated as a boolean <code>False</code> (for example, the empty list).</p> <p>In fact, every iterable, empty custom object is evaluated as <code>False</code> if it appears in boolean expression.</p> <p>Now suppose I have a class <code>foo</code> with attribute <code>bar</code>. How can I define its truth value, so that, say, it will be evaluated to <code>True if bar % 2 == 0</code> and <code>False</code> otherwise?</p> <p>For example:</p> <pre><code>myfoo = foo() myfoo.bar = 3 def a(myfoo): if foo: print "spam" else: print "eggs" </code></pre> <p>so, <code>a(myfoo)</code> should print <code>"eggs"</code>.</p>
18
2009-07-06T13:59:55Z
1,087,165
<p>Refer to the Python docs for <a href="https://docs.python.org/2/reference/datamodel.html#object.__nonzero__" rel="nofollow"><code>__nonzero__</code></a>.</p> <pre><code>class foo(object): def __nonzero__( self) : return self.bar % 2 == 0 def a(foo): if foo: print "spam" else: print "eggs" def main(): myfoo = foo() myfoo.bar = 3 a(myfoo) if __name__ == "__main__": main() </code></pre>
29
2009-07-06T14:04:57Z
[ "python", "boolean" ]
Boolean value of objects in Python
1,087,135
<p>As we know, Python has boolean values for objects: If a class has a <code>__len__</code> method, every instance of it for which <code>__len__()</code> happens to return 0 will be evaluated as a boolean <code>False</code> (for example, the empty list).</p> <p>In fact, every iterable, empty custom object is evaluated as <code>False</code> if it appears in boolean expression.</p> <p>Now suppose I have a class <code>foo</code> with attribute <code>bar</code>. How can I define its truth value, so that, say, it will be evaluated to <code>True if bar % 2 == 0</code> and <code>False</code> otherwise?</p> <p>For example:</p> <pre><code>myfoo = foo() myfoo.bar = 3 def a(myfoo): if foo: print "spam" else: print "eggs" </code></pre> <p>so, <code>a(myfoo)</code> should print <code>"eggs"</code>.</p>
18
2009-07-06T13:59:55Z
1,087,166
<p><strong>In Python &lt; 3.0 :</strong></p> <p>You have to use <a href="https://docs.python.org/2/reference/datamodel.html#object.__nonzero__" rel="nofollow"><code>__nonzero__</code></a> to achieve what you want. It's a method that is called automatically by Python when evaluating an object in a boolean context. It must return a boolean that will be used as the value to evaluate.</p> <p>E.G :</p> <pre><code>class Foo(object): def __init__(self, bar) : self.bar = bar def __nonzero__(self) : return self.bar % 2 == 0 if __name__ == "__main__": if (Foo(2)) : print "yess !" </code></pre> <p><strong>In Python => 3.0 :</strong></p> <p>Same thing, except the method has been renamed to the much more obvious <a href="https://docs.python.org/3/reference/datamodel.html#object.__bool__" rel="nofollow"><code>__bool__</code></a>.</p>
31
2009-07-06T14:05:09Z
[ "python", "boolean" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
1,087,413
<p><a href="https://launchpad.net/pyopenssl" rel="nofollow">pyOpenSSL</a> is an interface to the OpenSSL library. It should provide everything you need.</p>
0
2009-07-06T14:52:32Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
1,088,224
<p>You can use Twisted to verify certificates. The main API is <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.ssl.CertificateOptions.html">CertificateOptions</a>, which can be provided as the <code>contextFactory</code> argument to various functions such as <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.interfaces.IReactorSSL.listenSSL.html">listenSSL</a> and <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.interfaces.ITLSTransport.html#startTLS">startTLS</a>.</p> <p>Unfortunately, neither Python nor Twisted comes with a the pile of CA certificates required to actually do HTTPS validation, nor the HTTPS validation logic. Due to <a href="https://bugs.launchpad.net/pyopenssl/+bug/324857">a limitation in PyOpenSSL</a>, you can't do it completely correctly just yet, but thanks to the fact that almost all certificates include a subject commonName, you can get close enough.</p> <p>Here is a naive sample implementation of a verifying Twisted HTTPS client which ignores wildcards and subjectAltName extensions, and uses the certificate-authority certificates present in the 'ca-certificates' package in most Ubuntu distributions. Try it with your favorite valid and invalid certificate sites :).</p> <pre><code>import os import glob from OpenSSL.SSL import Context, TLSv1_METHOD, VERIFY_PEER, VERIFY_FAIL_IF_NO_PEER_CERT, OP_NO_SSLv2 from OpenSSL.crypto import load_certificate, FILETYPE_PEM from twisted.python.urlpath import URLPath from twisted.internet.ssl import ContextFactory from twisted.internet import reactor from twisted.web.client import getPage certificateAuthorityMap = {} for certFileName in glob.glob("/etc/ssl/certs/*.pem"): # There might be some dead symlinks in there, so let's make sure it's real. if os.path.exists(certFileName): data = open(certFileName).read() x509 = load_certificate(FILETYPE_PEM, data) digest = x509.digest('sha1') # Now, de-duplicate in case the same cert has multiple names. certificateAuthorityMap[digest] = x509 class HTTPSVerifyingContextFactory(ContextFactory): def __init__(self, hostname): self.hostname = hostname isClient = True def getContext(self): ctx = Context(TLSv1_METHOD) store = ctx.get_cert_store() for value in certificateAuthorityMap.values(): store.add_cert(value) ctx.set_verify(VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, self.verifyHostname) ctx.set_options(OP_NO_SSLv2) return ctx def verifyHostname(self, connection, x509, errno, depth, preverifyOK): if preverifyOK: if self.hostname != x509.get_subject().commonName: return False return preverifyOK def secureGet(url): return getPage(url, HTTPSVerifyingContextFactory(URLPath.fromString(url).netloc)) def done(result): print 'Done!', len(result) secureGet("https://google.com/").addCallback(done) reactor.run() </code></pre>
25
2009-07-06T17:29:48Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
1,441,779
<p><a href="http://chandlerproject.org/Projects/MeTooCrypto">M2Crypto</a> can <a href="http://www.heikkitoivonen.net/blog/2008/10/14/ssl-in-python-26/">do the validation</a>. You can also use <a href="http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/TwistedProtocolWrapper.py">M2Crypto with Twisted</a> if you like. The <a href="http://chandlerproject.org/">Chandler</a> desktop client <a href="http://svn.osafoundation.org/chandler/trunk/chandler/parcels/osaf/framework/certstore/ssl.py">uses Twisted for networking and M2Crypto for SSL</a>, including certificate validation.</p> <p>Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.</p> <p>I've also blogged on how to <a href="http://www.heikkitoivonen.net/blog/2008/09/30/root-certificates-for-python-programs-using-python/">get the certificates</a> Mozilla Firefox ships with in Python and usable with Python SSL solutions.</p>
8
2009-09-17T23:09:19Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
1,921,551
<p><a href="http://pycurl.sourceforge.net/">PycURL</a> does this beautifully.</p> <p>Below is a short example. It will throw a <code>pycurl.error</code> if something is fishy, where you get a tuple with error code and a human readable message.</p> <pre><code>import pycurl curl = pycurl.Curl() curl.setopt(pycurl.CAINFO, "myFineCA.crt") curl.setopt(pycurl.SSL_VERIFYPEER, 1) curl.setopt(pycurl.SSL_VERIFYHOST, 2) curl.setopt(pycurl.URL, "https://internal.stuff/") curl.perform() </code></pre> <p>You will probably want to configure more options, like where to store the results, etc. But no need to clutter the example with non-essentials.</p> <p>Example of what exceptions might be raised:</p> <pre><code>(60, 'Peer certificate cannot be authenticated with known CA certificates') (51, "common name 'CN=something.else.stuff,O=Example Corp,C=SE' does not match 'internal.stuff'") </code></pre> <p>Some links that I found useful are the libcurl-docs for setopt and getinfo.</p> <ul> <li><a href="http://curl.haxx.se/libcurl/c/curl_easy_setopt.html">http://curl.haxx.se/libcurl/c/curl_easy_setopt.html</a></li> <li><a href="http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html">http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html</a></li> </ul>
22
2009-12-17T12:48:51Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
3,551,700
<p>Here's an example script which demonstrates certificate validation:</p> <pre><code>import httplib import re import socket import sys import urllib2 import ssl class InvalidCertificateException(httplib.HTTPException, urllib2.URLError): def __init__(self, host, cert, reason): httplib.HTTPException.__init__(self) self.host = host self.cert = cert self.reason = reason def __str__(self): return ('Host %s returned an invalid certificate (%s) %s\n' % (self.host, self.reason, self.cert)) class CertValidatingHTTPSConnection(httplib.HTTPConnection): default_port = httplib.HTTPS_PORT def __init__(self, host, port=None, key_file=None, cert_file=None, ca_certs=None, strict=None, **kwargs): httplib.HTTPConnection.__init__(self, host, port, strict, **kwargs) self.key_file = key_file self.cert_file = cert_file self.ca_certs = ca_certs if self.ca_certs: self.cert_reqs = ssl.CERT_REQUIRED else: self.cert_reqs = ssl.CERT_NONE def _GetValidHostsForCert(self, cert): if 'subjectAltName' in cert: return [x[1] for x in cert['subjectAltName'] if x[0].lower() == 'dns'] else: return [x[0][1] for x in cert['subject'] if x[0][0].lower() == 'commonname'] def _ValidateCertificateHostname(self, cert, hostname): hosts = self._GetValidHostsForCert(cert) for host in hosts: host_re = host.replace('.', '\.').replace('*', '[^.]*') if re.search('^%s$' % (host_re,), hostname, re.I): return True return False def connect(self): sock = socket.create_connection((self.host, self.port)) self.sock = ssl.wrap_socket(sock, keyfile=self.key_file, certfile=self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs) if self.cert_reqs &amp; ssl.CERT_REQUIRED: cert = self.sock.getpeercert() hostname = self.host.split(':', 0)[0] if not self._ValidateCertificateHostname(cert, hostname): raise InvalidCertificateException(hostname, cert, 'hostname mismatch') class VerifiedHTTPSHandler(urllib2.HTTPSHandler): def __init__(self, **kwargs): urllib2.AbstractHTTPHandler.__init__(self) self._connection_args = kwargs def https_open(self, req): def http_class_wrapper(host, **kwargs): full_kwargs = dict(self._connection_args) full_kwargs.update(kwargs) return CertValidatingHTTPSConnection(host, **full_kwargs) try: return self.do_open(http_class_wrapper, req) except urllib2.URLError, e: if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1: raise InvalidCertificateException(req.host, '', e.reason.args[1]) raise https_request = urllib2.HTTPSHandler.do_request_ if __name__ == "__main__": if len(sys.argv) != 3: print "usage: python %s CA_CERT URL" % sys.argv[0] exit(2) handler = VerifiedHTTPSHandler(ca_certs = sys.argv[1]) opener = urllib2.build_opener(handler) print opener.open(sys.argv[2]).read() </code></pre>
14
2010-08-23T21:05:59Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
3,946,778
<p>I have added a distribution to the Python Package Index which makes the <code>match_hostname()</code> function from the Python 3.2 <code>ssl</code> package available on previous versions of Python.</p> <p><a href="http://pypi.python.org/pypi/backports.ssl_match_hostname/">http://pypi.python.org/pypi/backports.ssl_match_hostname/</a></p> <p>You can install it with:</p> <pre><code>pip install backports.ssl_match_hostname </code></pre> <p>Or you can make it a dependency listed in your project's <code>setup.py</code>. Either way, it can be used like this:</p> <pre><code>from backports.ssl_match_hostname import match_hostname, CertificateError ... sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3, cert_reqs=ssl.CERT_REQUIRED, ca_certs=...) try: match_hostname(sslsock.getpeercert(), hostname) except CertificateError, ce: ... </code></pre>
27
2010-10-15T23:06:57Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
6,028,764
<p>Jython DOES carry out certificate verification by default, so using standard library modules, e.g. httplib.HTTPSConnection, etc, with jython will verify certificates and give exceptions for failures, i.e. mismatched identities, expired certs, etc.</p> <p>In fact, you have to do some extra work to get jython to behave like cpython, i.e. to get jython to NOT verify certs. </p> <p>I have written a blog post on how to disable certificate checking on jython, because it can be useful in testing phases, etc.</p> <p>Installing an all-trusting security provider on java and jython.<br/> <a href="http://jython.xhaus.com/installing-an-all-trusting-security-provider-on-java-and-jython/" rel="nofollow">http://jython.xhaus.com/installing-an-all-trusting-security-provider-on-java-and-jython/</a></p>
4
2011-05-17T09:21:43Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
18,767,137
<p>Or simply make your life easier by using the <a href="https://pypi.python.org/pypi/requests" rel="nofollow">requests</a> library:</p> <pre><code>import requests requests.get('https://somesite.com', cert='/path/server.crt', verify=True) </code></pre> <p><a href="http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification" rel="nofollow">A few more words about its usage.</a></p>
11
2013-09-12T14:32:57Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
20,517,707
<p>I was having the same problem but wanted to minimize 3rd party dependencies (because this one-off script was to be executed by many users). My solution was to wrap a <code>curl</code> call and make sure that the exit code was <code>0</code>. Worked like a charm.</p>
0
2013-12-11T11:18:58Z
[ "python", "https", "ssl-certificate", "verification" ]
Validate SSL certificates with Python
1,087,227
<p>I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.</p> <p>Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.</p> <p><strike>Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?</strike></p> <p>How do I verify a certificate in Python?</p>
64
2009-07-06T14:17:34Z
28,325,763
<p>From release version 2.7.9/3.4.3 on, Python <strong>by default</strong> attempts to perform certificate validation.</p> <p>This has been proposed in PEP 467, which is worth a read: <a href="https://www.python.org/dev/peps/pep-0476/">https://www.python.org/dev/peps/pep-0476/</a></p> <p>The changes affect all relevant stdlib modules (urllib/urllib2, http, httplib).</p> <p>Relevant documentation:</p> <p><a href="https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection">https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection</a></p> <blockquote> <p>This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.</p> </blockquote> <p><a href="https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection">https://docs.python.org/3/library/http.client.html#http.client.HTTPSConnection</a></p> <blockquote> <p>Changed in version 3.4.3: This class now performs all the necessary certificate and hostname checks by default. To revert to the previous, unverified, behavior ssl._create_unverified_context() can be passed to the context parameter.</p> </blockquote> <p>Note that the new built-in verification is based on the <em>system-provided</em> certificate database. Opposed to that, the <a href="http://docs.python-requests.org">requests</a> package ships its own certificate bundle. Pros and cons of both approaches are discussed in the <a href="https://www.python.org/dev/peps/pep-0476/#trust-database"><em>Trust database</em> section of PEP 476</a>.</p>
8
2015-02-04T15:57:34Z
[ "python", "https", "ssl-certificate", "verification" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,265
<p>The <a href="http://en.wikipedia.org/wiki/Eval#Uses">Wikipedia article on <code>eval</code></a> is pretty informative, and details various uses.</p> <p>Some of the uses it suggests are:</p> <ul> <li>Evaluating mathematical expressions</li> <li><a href="http://en.wikipedia.org/wiki/Bootstrapping%5F%28compilers%29">Compiler bootstrapping</a></li> <li>Scripting (dynamic languages in general are very suitable to this)</li> <li>Language tutors</li> </ul>
13
2009-07-06T14:24:58Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,278
<p><code>eval()</code> is not normally very useful. One of the few things I have used it for (well, it was <code>exec()</code> actually, but it's pretty similar) was allowing the user to script an application that I wrote in Python. If it were written in something like C++, I would have to embed a Python interpreter in the application.</p>
1
2009-07-06T14:27:07Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,284
<p>In a program I once wrote, you had an input file where you could specify geometric parameters both as values and as python expressions of the previous values, eg:</p> <pre><code>a=10.0 b=5.0 c=math.log10(a/b) </code></pre> <p>A python parser read this input file and obtained the final data evaluating the values and the expressions using eval().</p> <p>I don't claim it to be good programming, but I did not have to drive a nuclear reactor.</p>
2
2009-07-06T14:28:12Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,295
<p>In the past I have used eval() to add a debugging interface to my application. I created a telnet service which dropped you into the environment of the running application. Inputs were run through eval() so you can interactively run Python commands in the application.</p>
5
2009-07-06T14:29:19Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,300
<p>You may want to use it to allow users to enter their own "scriptlets": <strong>small</strong> expressions (or even small functions), that can be used to customize the behavior of a <strong>complex</strong> system.<br /> In that context, and if you do not have to care too much for the security implications (e.g. you have an educated userbase), then eval() may be a good choice.</p>
11
2009-07-06T14:31:22Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,311
<p>Eval is a way to interact with the Python interpreter from within a program. You can pass literals to eval and it evaluates them as python expressions.</p> <p>For example - </p> <pre><code>print eval("__import__('os').getcwd()") </code></pre> <p>would return the current working directory.</p> <p>cheers</p>
1
2009-07-06T14:33:46Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,479
<p>I use it as a quick JSON parser ...</p> <pre><code>r=''' { "glossary": { "title": "example glossary" } } ''' print eval(r)['glossary']['title'] </code></pre>
-1
2009-07-06T15:03:08Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,625
<p><code>eval</code> and <code>exec</code> are handy quick-and-dirty way to get some source code dynamically, maybe munge it a bit, and then execute it -- but they're hardly ever the best way, especially in production code as opposed to "quick-and-dirty" prototypes &amp;c.</p> <p>For example, if I had to deal with such dynamic Python sources, I'd reach for the <a href="http://docs.python.org/library/ast.html#module-ast">ast</a> module -- <code>ast.literal_eval</code> is MUCH safer than <code>eval</code> (you can call it directly on a string form of the expression, if it's a one-off and relies on simple constants only, or do <code>node = ast.parse(source)</code> first, then keep the <code>node</code> around, perhaps munge it with suitable visitors e.g. for variable lookup, then <code>literal_eval</code> the node) -- or, once having put the node in proper shape and vetted it for security issues, I could <code>compile</code> it (yielding a code object) and build a new function object out of that. Far less simple (except that <code>ast.literal_eval</code> is just as simple as <code>eval</code> for the simplest cases!) but safer and preferable in production-quality code.</p> <p>For many tasks I've seen people (ab-)use <code>exec</code> and <code>eval</code> for, Python's powerful built-ins, such as <code>getattr</code> and <code>setattr</code>, indexing into <code>globals()</code>, &amp;c, provide preferable and in fact often simpler solutions. For specific uses such as parsing JSON, library modules such as <code>json</code> are better (e.g. see SilentGhost's comment on tinnitus' answer to this very question). Etc, etc...</p>
29
2009-07-06T15:30:21Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
1,087,675
<p>I use <code>exec</code> to create a system of plugins in Python.</p> <pre> try: exec ("from " + plugin_name + " import Plugin") myplugin = Plugin(module_options, config=config) except ImportError, message: fatal ("No such module " + plugin_name + \ " (or no Plugin constructor) in my Python path: " + str(message)) except Exception: fatal ("Module " + plugin_name + " cannot be loaded: " + \ str(sys.exc_type) + ": " + str(sys.exc_value) + \ ".\n May be a missing or erroneous option?") </pre> <p>With a plugin like:</p> <pre> class Plugin: def __init__ (self): pass def query(self, arg): ... </pre> <p>You will be able to call it like:</p> <pre> result = myplugin.query("something") </pre> <p>I do not think you can have plugins in Python without <code>exec</code>/<code>eval</code>.</p>
-2
2009-07-06T15:39:25Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
21,995,852
<p>I used it to input variable values to the main program:</p> <p>test.py var1=2 var2=True</p> <p>...</p> <pre><code>var1=0 var2=False for arg in sys.argv[1:]: exec(arg) </code></pre> <p>A crude way to allow keyword args in the main program. If there's a better way let me know!</p>
0
2014-02-24T18:22:29Z
[ "python", "dynamic", "eval" ]
Use of eval in Python?
1,087,255
<p>There is an <code>eval()</code> function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?</p>
15
2009-07-06T14:23:07Z
23,626,496
<p>eval() is for single sentence, while exec() is for multiple ones.</p> <p>usually we use them to add or visit some scripts just like bash shell.</p> <p>because of they can run some byte scripts in the memory, if you have some important data or script you can decode and unzip your 'secret' then do everything you wanna.</p>
-1
2014-05-13T08:42:40Z
[ "python", "dynamic", "eval" ]
Reportlab page x of y NumberedCanvas and Images
1,087,495
<p>I had been using the reportlab NumberedCanvas given at <a href="http://code.activestate.com/recipes/546511/" rel="nofollow">http://code.activestate.com/recipes/546511/</a> . However, when i try to build a PDF that contains Image flowables, the images do not show, although enough vertical space is left for the image to fit. Is there any solution for this?</p>
4
2009-07-06T15:05:23Z
1,088,029
<p>See <a href="http://code.activestate.com/recipes/576832/">my new, improved recipe</a> for this, which includes a simple test with images. Here's an excerpt from the recipe (which omits the test code):</p> <pre><code>from reportlab.pdfgen import canvas from reportlab.lib.units import mm class NumberedCanvas(canvas.Canvas): def __init__(self, *args, **kwargs): canvas.Canvas.__init__(self, *args, **kwargs) self._saved_page_states = [] def showPage(self): self._saved_page_states.append(dict(self.__dict__)) self._startPage() def save(self): """add page info to each page (page x of y)""" num_pages = len(self._saved_page_states) for state in self._saved_page_states: self.__dict__.update(state) self.draw_page_number(num_pages) canvas.Canvas.showPage(self) canvas.Canvas.save(self) def draw_page_number(self, page_count): self.setFont("Helvetica", 7) self.drawRightString(200*mm, 20*mm, "Page %d of %d" % (self._pageNumber, page_count)) </code></pre>
13
2009-07-06T16:51:06Z
[ "python", "reportlab" ]
Starting and Controlling an External Process via STDIN/STDOUT with Python
1,087,799
<p>I need to launch an external process that is to be controlled via messages sent back and forth via stdin and stdout. Using subprocess.Popen I am able to start the process but am unable to control the execution via stdin as I need to. </p> <p>The flow of what I'm trying to complete is to:</p> <ol> <li>Start the external process</li> <li>Iterate for some number of steps <ol> <li>Tell the external process to complete the next processing step by writing a new-line character to it's stdin</li> <li>Wait for the external process to signal it has completed the step by writing a new-line character to it's stdout</li> </ol></li> <li>Close the external process's stdin to indicate to the external process that execution has completed.</li> </ol> <p>I have come up with the following so far:</p> <pre><code>process=subprocess.Popen([PathToProcess],stdin=subprocess.PIPE,stdout=subprocess.PIPE); for i in xrange(StepsToComplete): print "Forcing step # %s"%i process.communicate(input='\n') </code></pre> <p>When I run the above code the '\n' is not communicated to the external process, and I never get beyond step #0. The code blocks at process.communicate() and does not proceed any further. I am using the communicate() method incorrectly? </p> <p>Also how would I implement the "wait until the external process writes a new line" piece of functionality?</p>
4
2009-07-06T16:03:57Z
1,087,883
<p>process.communicate(input='\n') is wrong. If you will notice from the Python docs, it writes your string to the stdin of the child, then reads all output from the child until the child exits. From doc.python.org:</p> <blockquote> <p>Popen.communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.</p> </blockquote> <p>Instead, you want to just write to the stdin of the child. Then read from it in your loop.</p> <p>Something more like:</p> <pre><code>process=subprocess.Popen([PathToProcess],stdin=subprocess.PIPE,stdout=subprocess.PIPE); for i in xrange(StepsToComplete): print "Forcing step # %s"%i process.stdin.write("\n") result=process.stdout.readline() </code></pre> <p>This will do something more like what you want.</p>
8
2009-07-06T16:18:06Z
[ "python", "subprocess" ]
Starting and Controlling an External Process via STDIN/STDOUT with Python
1,087,799
<p>I need to launch an external process that is to be controlled via messages sent back and forth via stdin and stdout. Using subprocess.Popen I am able to start the process but am unable to control the execution via stdin as I need to. </p> <p>The flow of what I'm trying to complete is to:</p> <ol> <li>Start the external process</li> <li>Iterate for some number of steps <ol> <li>Tell the external process to complete the next processing step by writing a new-line character to it's stdin</li> <li>Wait for the external process to signal it has completed the step by writing a new-line character to it's stdout</li> </ol></li> <li>Close the external process's stdin to indicate to the external process that execution has completed.</li> </ol> <p>I have come up with the following so far:</p> <pre><code>process=subprocess.Popen([PathToProcess],stdin=subprocess.PIPE,stdout=subprocess.PIPE); for i in xrange(StepsToComplete): print "Forcing step # %s"%i process.communicate(input='\n') </code></pre> <p>When I run the above code the '\n' is not communicated to the external process, and I never get beyond step #0. The code blocks at process.communicate() and does not proceed any further. I am using the communicate() method incorrectly? </p> <p>Also how would I implement the "wait until the external process writes a new line" piece of functionality?</p>
4
2009-07-06T16:03:57Z
1,103,295
<p>You could use Twisted, by using <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.interfaces.IReactorProcess.spawnProcess.html" rel="nofollow">reactor.spawnProcess</a> and <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.protocols.basic.LineReceiver.html" rel="nofollow">LineReceiver</a>.</p>
0
2009-07-09T11:29:37Z
[ "python", "subprocess" ]
testing python applications that use mysql
1,088,077
<p>I want to write some unittests for an application that uses MySQL. However, I do not want to connect to a real mysql database, but rather to a temporary one that doesn't require any SQL server at all.</p> <p>Any library (I could not find anything on google)? Any design pattern? Note that DIP doesn't work since I will still have to test the injected class.</p>
5
2009-07-06T17:00:00Z
1,088,090
<p>There isn't a good way to do that. You want to run your queries against a real MySQL server, otherwise you don't know if they will work or not.</p> <p>However, that doesn't mean you have to run them against a production server. We have scripts that create a Unit Test database, and then tear it down once the unit tests have run. That way we don't have to maintain a static test database, but we still get to test against the real server.</p>
8
2009-07-06T17:04:00Z
[ "python", "mysql", "unit-testing" ]
testing python applications that use mysql
1,088,077
<p>I want to write some unittests for an application that uses MySQL. However, I do not want to connect to a real mysql database, but rather to a temporary one that doesn't require any SQL server at all.</p> <p>Any library (I could not find anything on google)? Any design pattern? Note that DIP doesn't work since I will still have to test the injected class.</p>
5
2009-07-06T17:00:00Z
1,088,093
<p>I've used <a href="http://python-mock.sourceforge.net/" rel="nofollow">python-mock</a> and <a href="http://code.google.com/p/pymox/" rel="nofollow">mox</a> for such purposes (<em>extremely</em> lightweight tests that absolutely cannot require ANY SQL server), but for more extensive/in-depth testing, starting and populating a local instance of MySQL isn't too bad either.</p> <p>Unfortunately SQLite's SQL dialect and MySQL's differ enough that trying to use the former for tests is somewhat impractical, unless you're using some ORM (Django, SQLObject, SQLAlchemy, ...) that can hide the dialect differences.</p>
4
2009-07-06T17:04:44Z
[ "python", "mysql", "unit-testing" ]
Python: accessing DLL function using ctypes -- access by function *name* fails
1,088,085
<p><code>myPythonClient</code> (below) wants to invoke a <code>ringBell</code> function (loaded from a DLL using <code>ctypes</code>). However, attempting to access <code>ringBell</code> via its <em>name</em> results in an <code>AttributeError</code>. Why?</p> <p><code>RingBell.h</code> contains</p> <pre><code>namespace MyNamespace { class MyClass { public: static __declspec(dllexport) int ringBell ( void ) ; } ; } </code></pre> <p><code>RingBell.cpp</code> contains</p> <pre><code>#include &lt;iostream&gt; #include "RingBell.h" namespace MyNamespace { int __cdecl MyClass::ringBell ( void ) { std::cout &lt;&lt; "\a" ; return 0 ; } } </code></pre> <p><code>myPythonClient.py</code> contains</p> <pre><code>from ctypes import * cdll.RingBell[1]() # this invocation works fine cdll.RingBell.ringBell() # however, this invocation errors out # AttributeError: function 'ringBell' not found </code></pre>
5
2009-07-06T17:02:09Z
1,088,111
<p>Perhaps because the C++ name is mangled by the compiler and not exported from the DLL as <code>RingBell</code>. Have you checked that it appears in the exported names exactly like that?</p>
6
2009-07-06T17:08:32Z
[ "python", "dll", "ctypes", "attributeerror" ]
Python: accessing DLL function using ctypes -- access by function *name* fails
1,088,085
<p><code>myPythonClient</code> (below) wants to invoke a <code>ringBell</code> function (loaded from a DLL using <code>ctypes</code>). However, attempting to access <code>ringBell</code> via its <em>name</em> results in an <code>AttributeError</code>. Why?</p> <p><code>RingBell.h</code> contains</p> <pre><code>namespace MyNamespace { class MyClass { public: static __declspec(dllexport) int ringBell ( void ) ; } ; } </code></pre> <p><code>RingBell.cpp</code> contains</p> <pre><code>#include &lt;iostream&gt; #include "RingBell.h" namespace MyNamespace { int __cdecl MyClass::ringBell ( void ) { std::cout &lt;&lt; "\a" ; return 0 ; } } </code></pre> <p><code>myPythonClient.py</code> contains</p> <pre><code>from ctypes import * cdll.RingBell[1]() # this invocation works fine cdll.RingBell.ringBell() # however, this invocation errors out # AttributeError: function 'ringBell' not found </code></pre>
5
2009-07-06T17:02:09Z
1,088,142
<p>Your C++ compiler is mangling the names of all externally visible objects to reflect (as well as their underlying names) their namespaces, classes, and signatures (that's how overloading becomes possible).</p> <p>In order to avoid this mangling, you need an <code>extern "C"</code> on externally visible names that you want to be visible from non-C++ code (and therefore such names cannot be overloaded, nor in C++ standard can they be inline, within namespaces, or within classes, though some C++ compilers extend the standard in some of these directions).</p>
9
2009-07-06T17:13:35Z
[ "python", "dll", "ctypes", "attributeerror" ]
Python: accessing DLL function using ctypes -- access by function *name* fails
1,088,085
<p><code>myPythonClient</code> (below) wants to invoke a <code>ringBell</code> function (loaded from a DLL using <code>ctypes</code>). However, attempting to access <code>ringBell</code> via its <em>name</em> results in an <code>AttributeError</code>. Why?</p> <p><code>RingBell.h</code> contains</p> <pre><code>namespace MyNamespace { class MyClass { public: static __declspec(dllexport) int ringBell ( void ) ; } ; } </code></pre> <p><code>RingBell.cpp</code> contains</p> <pre><code>#include &lt;iostream&gt; #include "RingBell.h" namespace MyNamespace { int __cdecl MyClass::ringBell ( void ) { std::cout &lt;&lt; "\a" ; return 0 ; } } </code></pre> <p><code>myPythonClient.py</code> contains</p> <pre><code>from ctypes import * cdll.RingBell[1]() # this invocation works fine cdll.RingBell.ringBell() # however, this invocation errors out # AttributeError: function 'ringBell' not found </code></pre>
5
2009-07-06T17:02:09Z
8,473,993
<p>All is working now :) To summarize your posts:</p> <p>Write DLL in C++:</p> <pre><code>// Header extern "C" { // Name in DLL will be "MyAdd" - but you won't be able to find parameters etc... __declspec(dllexport) int MyAdd(int a, int b); } // Name will be with lot of prefixes but some other info is provided - IMHO better approach __declspec(dllexport) int MyAdd2(int a, int b); //.cpp Code __declspec(dllexport) int MyAdd(int a, int b) { return a+b; } __declspec(dllexport) int MyAdd2(int a, int b) { return a+b; } </code></pre> <p>Then you can use program link.exe to see real function name in dll. link.exe is for example in MSVC2010 here:</p> <pre><code>c:\program files\microsoft visual studio 10.0\VC\bin\link.exe </code></pre> <p>use:</p> <pre><code>link /dump /exports yourFileName.dll </code></pre> <p>you see Something like:</p> <pre><code>ordinal hint RVA name 1 0 00001040 ?MyAdd2@@YAHHH@Z = ?MyAdd2@@YAHHH@Z (int __cdecl MyAdd2(int,int)) 2 1 00001030 MyAdd = _MyAdd </code></pre> <p>Then in python you can import it as: </p> <pre><code>import ctypes mc = ctypes.CDLL('C:\\testDll3.dll') #mc.MyAdd2(1,2) # this Won't Work - name is different in dll myAdd2 = getattr(mc,"?MyAdd2@@YAHHH@Z") #to find name use: link.exe /dump /exports fileName.dll print myAdd2(1,2) #p1 = ctypes.c_int (1) #use rather c types print mc[1](2,3) # use indexing - can be provided using link.exe print mc.MyAdd(4,5) print mc[2](6,7) # use indexing - can be provided using link.exe </code></pre>
5
2011-12-12T12:02:01Z
[ "python", "dll", "ctypes", "attributeerror" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
1,088,359
<p><a href="http://docs.python.org/library/ftplib.html?highlight=ftplib#ftplib.FTP.dir"><code>FTP.dir</code></a> returns a directory listing, that you can parse with a callback function to find out whether it's a directory. For example, like this:</p> <pre><code>def parse(line): if line[0] == 'd': print(line.rpartition(' ')[2]) # gives you the name of a directory ftp.dir(parse) </code></pre>
5
2009-07-06T17:55:52Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
1,088,393
<pre><code>def is_file(filename): return ftp.size(filename) is not None </code></pre> <p>This works because ftp.size returns None if it is a directory.</p>
1
2009-07-06T18:01:04Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
1,088,645
<pre><code>def is_file(filename): current = ftp.pwd() try: ftp.cwd(filename) except: ftp.cwd(current) return True ftp.cwd(current) return False </code></pre> <p>Here is another solution. Half way writing it out I realized it has a problem. If you don't have permission to change to a folder, it'll read it as a file instead. It'll work if you have access to any folder. </p> <p>I still posted it because maybe it'll give some ideas.</p>
0
2009-07-06T18:49:41Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
1,985,617
<p>FTP is quite a rudimentary protocol and there's no built-in protocol query allowing you to get the type (file, dir) of each node, so a heuristic like the one you found is the only solution.</p> <p>If getting the size of each node doesn't work, perhaps you should consider calling <a href="http://docs.python.org/library/ftplib.html#ftplib.FTP.nlst" rel="nofollow"><code>FTP.nlst()</code></a> on each of those nodes: those that error out will be files rather than dirs.</p>
6
2009-12-31T14:28:08Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
8,474,577
<p>You can use MLST command:</p> <pre><code>import ftplib f = ftplib.FTP() f.connect("localhost") f.login() print f.sendcmd('MLST /') </code></pre> <p>Against <a href="http://code.google.com/p/pyftpdlib/" rel="nofollow">pyftpdlib server</a> the code above prints:</p> <pre><code>250-Listing "/": modify=20111212124834;perm=el;size=12288;type=dir;unique=807g100001; / 250 End MLST. </code></pre> <p>What you have to do is parse that string and look for "type=dir" or "type=cdir" (current dir, as in ".") or "type=pdir" (parent dir as in "..") via a regular expression. If you get a match, it means that the provided path refers to a directory.</p>
1
2011-12-12T12:51:09Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
10,658,892
<p>I have used this when dealing with ftplib:</p> <pre><code>import ftplib from ftplib import FTP ftp=FTP("ftp address") ftp.login("user","password") path = "/is/this/a/file/or/a/folder/" try: ftp.cwd(path) print "it's a folder!" except ftplib.error_perm: print "it's not a folder!" </code></pre>
1
2012-05-18T19:52:42Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
16,729,691
<p>This is what I use for finding the directories in a given directory. I return the directory names as a set because I use sets later on in the program, but you could leave off the set creation at the end and return the directory names as a list, tuple, etc.</p> <pre class="lang-py prettyprint-override"><code>def get_directories(ftp_server): """ Returns a set of directories in the current directory on the FTP server Stdout output of ftp_server.dir() is redirected to an IO object and then reset, because ftp_server.dir() only prints its results to stdout. @param ftp_server: Open connection to FTP server @return: Set of directory names """ # Redirect stdout old_stdout = sys.stdout sys.stdout = new_stdout = StringIO() # Get directory listing ftp_server.dir() # Reset stdout sys.stdout = old_stdout directory_listing = new_stdout.getvalue().split("\n") # Directories are listed starting with "d" for "directory" only_directories = (x for x in directory_listing if x.startswith("d")) # This only deals with directory names without spaces. directory_names = set(dirname.split()[-1] for dirname in only_directories) return directory_names </code></pre>
1
2013-05-24T07:24:38Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
27,321,502
<p>I have found a solution, but it may not be the best and I think it can be helpful for you.</p> <pre><code>&gt; def isfile(remote_name): &gt; try: &gt; ftp.sendcmd('MDTM ' + remote_name) &gt; except: &gt; return False &gt; else: &gt; return True </code></pre> <p>This function will return TRUE if 'remote_name' is a regular file, otherwise will return False.</p>
0
2014-12-05T17:29:33Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
28,141,179
<p>All files have an extension, so by using split('.') it can be broken into a list of size 2. While for directories the size of list will be one after using split('.'). So by checking size of list we can identify if its a file or a directory.</p> <pre><code>os.chdir(r"path") ftp = ftplib.FTP('ftp.some.server') ftp.login('username','password') filelist=ftp.nlst() for file in filelist: fildir=file.split('.') filsize=len(fildir) if(filsize&gt;1): ftp.retrbinary('RETR %s' %file, open(file, 'wb').write) ftp.close() </code></pre>
-2
2015-01-25T20:37:04Z
[ "python", "ftp", "ftplib" ]
ftplib checking if a file is a folder?
1,088,336
<p>How can i check if a file on a remote ftp is a folder or not using ftplib?</p> <p>Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?</p> <p>Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)</p> <p>What should i do?</p>
11
2009-07-06T17:49:49Z
39,980,353
<p>There are not "isdir" and "isfile" definitions in ftplib. If you don't have to use ftplib, i recommend you to use <a href="http://ftputil.sschwarzer.net/trac/wiki/Documentation" rel="nofollow">ftputil</a>. </p> <p>First of all you have to install ftputil package. To achive this, use this command: <code>python -m pip install ftputil</code>. After the installation, you can import the library to your code. I think it's enough explanation. So, let's go to the implementation:</p> <pre><code>import ftputil with ftputil.FTPHost("host", "username", "password") as ftp_host: ftp_host.chdir("/directory/") list = ftp_host.listdir(ftp_host.curdir) for fname in list: if ftp_host.path.isdir(fname): print(fname + " is a directory") else: print(fname + " is not a directory") </code></pre>
0
2016-10-11T15:01:01Z
[ "python", "ftp", "ftplib" ]
Sorting a Python list by key... while checking for string OR float?
1,088,392
<p>Ok, I've got a list like this (just a sample of data):</p> <pre><code>data = {"NAME": "James", "RANK": "3.0", "NUM": "27.5" ... } </code></pre> <p>Now, if I run something like this:</p> <pre><code>sortby = "NAME" //this gets passed to the function, hence why I am using a variable sortby instead data.sort(key=itemgetter(sortby)) </code></pre> <p>I get all the strings sorted properly - alphabetically.</p> <p>However, when "sortby" is any of the floating values (RANK or NUM or any other), sort is done again, alphabetically, instead of numerically, so my sorted list looks something like this then:</p> <p>0.441 101.404 107.558 107.558 108.48 108.945 11.195 12.143 12.801 131.73</p> <p>which is obviously wrong.</p> <p>Now, how can I do a sort like that (most efficiently in terms of speed and resources/computations taken) but have it cast the value somehow to float when it's a float, and leave it as a string when it's a string... possible? And no, removing quotes from float values in the list is not an option - I don't have control over the source list, unfortunately (and I know, that would've been an easy solution).</p>
1
2009-07-06T18:00:59Z
1,088,433
<p>Slightly more verbose than just passing a field name, but this is an option:</p> <pre><code>sort_by_name = lambda x: x['name'] sort_by_rank = lambda x: float(x['RANK']) # etc... data.sort(key=sort_by_rank) </code></pre> <p>If the data is much more dense than what you've posted, you might want a separate dictionary mapping field names to data types, and then a factory function to produce sorters suitable for the <code>key</code> argument to <code>list.sort()</code></p>
0
2009-07-06T18:09:23Z
[ "python", "list", "sorting" ]
Sorting a Python list by key... while checking for string OR float?
1,088,392
<p>Ok, I've got a list like this (just a sample of data):</p> <pre><code>data = {"NAME": "James", "RANK": "3.0", "NUM": "27.5" ... } </code></pre> <p>Now, if I run something like this:</p> <pre><code>sortby = "NAME" //this gets passed to the function, hence why I am using a variable sortby instead data.sort(key=itemgetter(sortby)) </code></pre> <p>I get all the strings sorted properly - alphabetically.</p> <p>However, when "sortby" is any of the floating values (RANK or NUM or any other), sort is done again, alphabetically, instead of numerically, so my sorted list looks something like this then:</p> <p>0.441 101.404 107.558 107.558 108.48 108.945 11.195 12.143 12.801 131.73</p> <p>which is obviously wrong.</p> <p>Now, how can I do a sort like that (most efficiently in terms of speed and resources/computations taken) but have it cast the value somehow to float when it's a float, and leave it as a string when it's a string... possible? And no, removing quotes from float values in the list is not an option - I don't have control over the source list, unfortunately (and I know, that would've been an easy solution).</p>
1
2009-07-06T18:00:59Z
1,088,444
<p>if you cant save your data properly ( floats as <em>floats</em> ), something like this</p> <pre><code>sorters = { "NAME" : itemgetter("NAME"), "RANK" : lambda x: float(x["RANK"]), "NUM" : lambda x: float(x["NUM"]) } data.sort(key=sorters[sortby]) </code></pre>
4
2009-07-06T18:11:25Z
[ "python", "list", "sorting" ]
Sorting a Python list by key... while checking for string OR float?
1,088,392
<p>Ok, I've got a list like this (just a sample of data):</p> <pre><code>data = {"NAME": "James", "RANK": "3.0", "NUM": "27.5" ... } </code></pre> <p>Now, if I run something like this:</p> <pre><code>sortby = "NAME" //this gets passed to the function, hence why I am using a variable sortby instead data.sort(key=itemgetter(sortby)) </code></pre> <p>I get all the strings sorted properly - alphabetically.</p> <p>However, when "sortby" is any of the floating values (RANK or NUM or any other), sort is done again, alphabetically, instead of numerically, so my sorted list looks something like this then:</p> <p>0.441 101.404 107.558 107.558 108.48 108.945 11.195 12.143 12.801 131.73</p> <p>which is obviously wrong.</p> <p>Now, how can I do a sort like that (most efficiently in terms of speed and resources/computations taken) but have it cast the value somehow to float when it's a float, and leave it as a string when it's a string... possible? And no, removing quotes from float values in the list is not an option - I don't have control over the source list, unfortunately (and I know, that would've been an easy solution).</p>
1
2009-07-06T18:00:59Z
1,088,538
<p>If you want a general function which you can pass as a parameter to <code>sort(key=XXX)</code>, then here's a candidate complete with test:</p> <pre><code>DATA = [ { 'name' : 'A', 'value' : '10.0' }, { 'name' : 'B', 'value' : '2.0' }, ] def get_attr(name): def inner_func(o): try: rv = float(o[name]) except ValueError: rv = o[name] return rv return inner_func for attrname in ('name', 'value'): DATA.sort(key=get_attr(attrname)) print "%r-sorted: %s" % (attrname, DATA) </code></pre> <p>When you run the above script, you get:</p> <pre><code>'name'-sorted: [{'name': 'A', 'value': '10.0'}, {'name': 'B', 'value': '2.0'}] 'value'-sorted: [{'name': 'B', 'value': '2.0'}, {'name': 'A', 'value': '10.0'}] </code></pre>
7
2009-07-06T18:29:42Z
[ "python", "list", "sorting" ]
Adding attributes into Django Model's Meta class
1,088,431
<p>I'm writing a mixin which will allow my Models to be easily translated into a deep dict of values (kind of like .values(), but traversing relationships). The cleanest place to do the definitions of these seems to be in the models themselves, a la:</p> <pre><code>class Person(models.Model, DeepValues): name = models.CharField(blank=True, max_length=100) tribe = models.ForeignKey('Tribes') class Meta: schema = { 'name' : str, 'tribe' : { 'name' : str } } Person.objects.all().deep_values() =&gt; { 'name' : 'Andrey Fedorov', 'tribe' : { 'name' : 'Mohicans' } } </code></pre> <p>However, Django complains about my including this in <code>class Meta</code> with:</p> <pre><code>TypeError: 'class Meta' got invalid attribute(s): schema </code></pre> <p>(entire stack trace <a href="http://gist.github.com/76cef1f8aea0ce92cb24">here</a>)</p> <p>Now, I suppose I could elaborately override this in my mixin, but is there a more elegant way of storing this information?</p>
24
2009-07-06T18:08:21Z
1,088,649
<p>I don't know about elegant, but one pragmatic way is:</p> <pre><code>import django.db.models.options as options options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('schema',) </code></pre> <p>Obviously, this would break if Django ever added a 'schema' attribute of its own. But hey, it's a thought...you could always pick an attribute name which is less likely to clash.</p>
36
2009-07-06T18:50:36Z
[ "python", "django", "django-models", "metadata" ]
HTML inside node using ElementTree
1,088,476
<p>I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows:</p> <pre><code>&lt;Course&gt; &lt;Description&gt;Line 1&lt;br /&gt;Line 2&lt;/Description&gt; &lt;/Course&gt; </code></pre> <p>Now, supposing _course is an Element variable which hold this Couse element. I want to access this course's description, so I do:</p> <pre><code>desc = _course.find("Description").text; </code></pre> <p>But then desc only contains "Line 1". I read something about the .tail attribute, so I tried also:</p> <pre><code>desc = _course.find("Description").tail; </code></pre> <p>And I get the same output. What should I do to make desc be "Line 1<br />Line 2" (or literally anything between and )? In other words, I'm looking for something similar to the .innerText property in C# (and many other languages I guess).</p>
3
2009-07-06T18:17:47Z
1,088,498
<p>Do you have any control over the creation of the xml file? The contents of xml tags which contain xml tags (or similar), or markup chars ('<code>&lt;</code>', etc) should be encoded to avoid this problem. You can do this with either:</p> <ul> <li>a <a href="http://en.wikipedia.org/wiki/Cdata" rel="nofollow">CDATA</a> section</li> <li>Base64 or some other encoding (which doesn't include xml reserved characters)</li> <li>Entity encoding ('<code>&lt;</code>' <code>==</code> '<code>&amp;lt;</code>')</li> </ul> <p>If you can't make these changes, and ElementTree can't ignore tags not included in the xml schema, then you will have to pre-process the file. Of course, you're out of luck if the schema overlaps html.</p>
3
2009-07-06T18:22:37Z
[ "python", "html", "xml", "elementtree" ]
HTML inside node using ElementTree
1,088,476
<p>I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows:</p> <pre><code>&lt;Course&gt; &lt;Description&gt;Line 1&lt;br /&gt;Line 2&lt;/Description&gt; &lt;/Course&gt; </code></pre> <p>Now, supposing _course is an Element variable which hold this Couse element. I want to access this course's description, so I do:</p> <pre><code>desc = _course.find("Description").text; </code></pre> <p>But then desc only contains "Line 1". I read something about the .tail attribute, so I tried also:</p> <pre><code>desc = _course.find("Description").tail; </code></pre> <p>And I get the same output. What should I do to make desc be "Line 1<br />Line 2" (or literally anything between and )? In other words, I'm looking for something similar to the .innerText property in C# (and many other languages I guess).</p>
3
2009-07-06T18:17:47Z
1,088,517
<p>Characters like "&lt;" and "&amp;" are illegal in XML elements.</p> <p>"&lt;" will generate an error because the parser interprets it as the start of a new element.</p> <p>"&amp;" will generate an error because the parser interprets it as the start of an character entity.</p> <p>Some text, like JavaScript code, contains a lot of "&lt;" or "&amp;" characters. To avoid errors script code can be defined as CDATA.</p> <p>Everything inside a CDATA section is ignored by the parser.</p> <p>A CDATA section starts with "":</p> <p>More information on: <a href="http://www.w3schools.com/xmL/xml_cdata.asp" rel="nofollow">http://www.w3schools.com/xmL/xml_cdata.asp</a></p> <p>Hope this helps!</p>
1
2009-07-06T18:25:28Z
[ "python", "html", "xml", "elementtree" ]
HTML inside node using ElementTree
1,088,476
<p>I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows:</p> <pre><code>&lt;Course&gt; &lt;Description&gt;Line 1&lt;br /&gt;Line 2&lt;/Description&gt; &lt;/Course&gt; </code></pre> <p>Now, supposing _course is an Element variable which hold this Couse element. I want to access this course's description, so I do:</p> <pre><code>desc = _course.find("Description").text; </code></pre> <p>But then desc only contains "Line 1". I read something about the .tail attribute, so I tried also:</p> <pre><code>desc = _course.find("Description").tail; </code></pre> <p>And I get the same output. What should I do to make desc be "Line 1<br />Line 2" (or literally anything between and )? In other words, I'm looking for something similar to the .innerText property in C# (and many other languages I guess).</p>
3
2009-07-06T18:17:47Z
6,653,844
<p>You are trying to read the tail attribute from the wrong element. Try</p> <pre><code>desc = _course.find("br").tail; </code></pre> <p>The tail attribute is used to store trailing text nodes when reading mixed-content XML files; text that follows directly after an element are stored in the tail attribute for that element:</p> <pre> &lt;tag&gt;&lt;elem&gt;this goes into elem&#39;s text attribute&lt;/elem&gt;this goes into elem&#39;s tail attribute&lt;/tag&gt; </pre> <p>Simple code snippet to print text and tail attributes from all elements in xml/xhtml.</p> <pre> import xml.etree.ElementTree as ET def processElem(elem): if elem.text is not None: print elem.text for child in elem: processElem(child) if child.tail is not None: print child.tail xml = '''&lt;Course&gt; &lt;Description&gt;Line 1&lt;br /&gt;Line 2 &lt;span&gt;child text &lt;/span&gt;child tail&lt;/Description&gt; &lt;/Course&gt;''' root = ET.fromstring(xml) processElem(root) </pre> <p>Output:</p> <pre> Line 1 Line 2 child text child tail </pre> <p>See <a href="http://code.activestate.com/recipes/498286-elementtree-text-helper/" rel="nofollow">http://code.activestate.com/recipes/498286-elementtree-text-helper/</a> for a better solution. It can be modified to suit.</p> <p>P.S. I changed my name from user839338 as quoted in the next post</p>
3
2011-07-11T17:13:53Z
[ "python", "html", "xml", "elementtree" ]
HTML inside node using ElementTree
1,088,476
<p>I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows:</p> <pre><code>&lt;Course&gt; &lt;Description&gt;Line 1&lt;br /&gt;Line 2&lt;/Description&gt; &lt;/Course&gt; </code></pre> <p>Now, supposing _course is an Element variable which hold this Couse element. I want to access this course's description, so I do:</p> <pre><code>desc = _course.find("Description").text; </code></pre> <p>But then desc only contains "Line 1". I read something about the .tail attribute, so I tried also:</p> <pre><code>desc = _course.find("Description").tail; </code></pre> <p>And I get the same output. What should I do to make desc be "Line 1<br />Line 2" (or literally anything between and )? In other words, I'm looking for something similar to the .innerText property in C# (and many other languages I guess).</p>
3
2009-07-06T18:17:47Z
6,711,116
<p>Inspired by <a href="http://stackoverflow.com/questions/1088476/html-inside-node-using-elementtree/6653844#6653844">user839338's answer</a>, I wen't and looked for a reasonable solution, which looks a bit like this.</p> <pre><code>&gt;&gt;&gt; from xml.etree import ElementTree as etree &gt;&gt;&gt; corpus = '''&lt;Course&gt; ... &lt;Description&gt;Line 1&lt;br /&gt;Line 2&lt;/Description&gt; ... &lt;/Course&gt;''' &gt;&gt;&gt; &gt;&gt;&gt; doc = etree.fromstring(corpus) &gt;&gt;&gt; desc = doc.find("Description") &gt;&gt;&gt; desc.tag = 'html' &gt;&gt;&gt; etree.tostring(desc) '&lt;html&gt;Line 1&lt;br/&gt;Line 2&lt;/html&gt;\n' &gt;&gt;&gt; </code></pre> <p>There's no simple way to eliminate the surrounding tag (originally <code>&lt;Description&gt;</code>), but it's easily modified into something that could be used as needed, for instance <code>&lt;div&gt;</code> or <code>&lt;span&gt;</code></p>
1
2011-07-15T17:46:02Z
[ "python", "html", "xml", "elementtree" ]
Python Libraries for FTP Upload/Download?
1,088,518
<p>Okay so a bit of forward:</p> <p>We have a service/daemon written in python that monitors remote ftp sites. These sites are not under our command, some of them we do NOT have del/rename/write access, some also are running extremely old ftp software. Such that certain commands do not work. There is no standardization among any of these ftp's, and they are out of our control(government). </p> <p>About a year ago i wrote a ftp wrapper library for in house that basically adds in stuff like resume upload/resume download/verifying files are not currently being written to, etc. The problem is we soon found out is that due to so many of the ftp servers running werid/non standard software we were constantly fighting with the wrapper library/ftplib. </p> <p>Basically I've given up on ftplib. Is there an alternative? I've looked at most of the ftp alternatives all of them are missing one or another key component of functionality. </p> <p>What ever the choice is, it must run for python 2.5.2 (we cannot change). and must run on Linux/Windows/HP-UX.</p> <p>Update:</p> <p>Sorry i forgot to tell you alternatives i looked at:</p> <ol> <li>ftputil, problem is it does not support resume upload/download and stuff like partially downloading files given an offset.</li> <li>Pycurl looked good, i'll look at it again.</li> </ol>
1
2009-07-06T18:26:01Z
1,088,557
<p>You may have better luck with one of the cURL bindings such as <a href="http://pycurl.sourceforge.net/" rel="nofollow">pycURL</a>.</p>
1
2009-07-06T18:33:47Z
[ "python", "ftp", "ftplib" ]
Python Libraries for FTP Upload/Download?
1,088,518
<p>Okay so a bit of forward:</p> <p>We have a service/daemon written in python that monitors remote ftp sites. These sites are not under our command, some of them we do NOT have del/rename/write access, some also are running extremely old ftp software. Such that certain commands do not work. There is no standardization among any of these ftp's, and they are out of our control(government). </p> <p>About a year ago i wrote a ftp wrapper library for in house that basically adds in stuff like resume upload/resume download/verifying files are not currently being written to, etc. The problem is we soon found out is that due to so many of the ftp servers running werid/non standard software we were constantly fighting with the wrapper library/ftplib. </p> <p>Basically I've given up on ftplib. Is there an alternative? I've looked at most of the ftp alternatives all of them are missing one or another key component of functionality. </p> <p>What ever the choice is, it must run for python 2.5.2 (we cannot change). and must run on Linux/Windows/HP-UX.</p> <p>Update:</p> <p>Sorry i forgot to tell you alternatives i looked at:</p> <ol> <li>ftputil, problem is it does not support resume upload/download and stuff like partially downloading files given an offset.</li> <li>Pycurl looked good, i'll look at it again.</li> </ol>
1
2009-07-06T18:26:01Z
1,088,625
<p>You don't mention which alternatives you've looked at already. Is ftputil one of them?</p> <p><a href="http://ftputil.sschwarzer.net/trac/wiki/Documentation" rel="nofollow">http://ftputil.sschwarzer.net/trac/wiki/Documentation</a></p> <p>If you're trying to code around edge cases from various server implementations, you might be better off looking at the code used by Mozilla/Firefox. I imagine this is one of the things they have to deal with constantly.</p>
1
2009-07-06T18:47:08Z
[ "python", "ftp", "ftplib" ]
App Engine db.model reference question
1,088,678
<p>How can I get at the Labels data from within my Task model?</p> <pre><code>class Task(db.Model): title = db.StringProperty() class Label(db.Model): name = db.StringProperty() class Tasklabel(db.Model): task = db.ReferenceProperty(Task) label = db.ReferenceProperty(Label) </code></pre> <p>creating the association is no problem, but how can I get at the labels associated with a task like:</p> <pre><code>task = Task.get('...') for label in task.labels </code></pre>
0
2009-07-06T18:57:05Z
1,088,766
<p>Don't you want a <a href="http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html#Lists" rel="nofollow">ListProperty</a> on Task like this to do a many-to-many?</p> <pre><code>class Label(db.Model) name = db.StringProperty() @property def members(self): return Task.gql("WHERE labels = :1", self.key()) class Task(db.Model) title = db.StringProperty(); labels = db.ListProperty(db.Key) </code></pre> <p>Then you could do</p> <pre><code>foo_label = Label.gql("WHERE name = 'foo'").get() task1 = Task.gql("WHERE title = 'task 1'").get() if foo_label.key() not in task1.labels: task1.labels.append(foo_label.key()) task1.put() </code></pre> <p>There's a thorough article about modeling entity relationships on <a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">Google code</a>. I stole the code above from this article.</p>
1
2009-07-06T19:17:38Z
[ "python", "google-app-engine" ]
App Engine db.model reference question
1,088,678
<p>How can I get at the Labels data from within my Task model?</p> <pre><code>class Task(db.Model): title = db.StringProperty() class Label(db.Model): name = db.StringProperty() class Tasklabel(db.Model): task = db.ReferenceProperty(Task) label = db.ReferenceProperty(Label) </code></pre> <p>creating the association is no problem, but how can I get at the labels associated with a task like:</p> <pre><code>task = Task.get('...') for label in task.labels </code></pre>
0
2009-07-06T18:57:05Z
1,089,470
<p>This worked for me with your current datamodel:</p> <pre><code>taskObject = db.Query(Task).get() for item in taskObject.tasklabel_set: item.label.name </code></pre> <p>Or you could remove the Label class and just do a one-to-many relationship between Task and TaskLabel:</p> <pre><code>class Task(db.Model): title = db.StringProperty() class TaskLabel(db.Model): task = db.ReferenceProperty(Task) label = db.StringProperty() </code></pre> <p>Then</p> <pre><code>taskObject = db.Query(Task).get() for item in taskObject.tasklabel_set: item.label </code></pre> <p>Here is a tip from the Google article on modeling relationships in the datastore</p> <blockquote> <p>By defining it as a ReferenceProperty, you have created a property that can only be assigned values of type 'Task'. Every time you define a reference property, it creates an implicit collection property on the referenced class. By default, this collection is called _set. In this case, it would make a property Task.tasklabel_set.</p> </blockquote> <p>The article can be found <a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">here</a>.</p> <p>I also recommend playing around with this code in the interactive console on the dev appserver.</p>
2
2009-07-06T22:20:21Z
[ "python", "google-app-engine" ]
Django Reporting Options
1,088,738
<p>I want to create a new "Business" application using the Django framework. Any suggestions as to what I can use as a reporting framework? The application will need to generate reports on various business entities including summaries, totals, grouping, etc. Basically, is there a Crystal reports-like equivalent for Django/Python?</p>
9
2009-07-06T19:11:27Z
1,088,917
<p>These are just HTML templates with ordinary view functions.</p> <p>This doesn't require much: Parameters come in from a form; write the query in the view function, passing the queryset to the template. The template presents the report.</p> <p>Why would you need something more than this? </p> <p>You can use <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#list-detail-generic-views" rel="nofollow">generic list/detail views</a> to save yourself from having to write as much code. If you go this route, you provide the query set and the template to a generic view that handles some of the processing for you.</p> <p>Since you must write the query in Crystal reports or Django, you're not really getting much leverage from a "reporting" tool.</p>
1
2009-07-06T19:56:09Z
[ "python", "django", "reporting" ]
Django Reporting Options
1,088,738
<p>I want to create a new "Business" application using the Django framework. Any suggestions as to what I can use as a reporting framework? The application will need to generate reports on various business entities including summaries, totals, grouping, etc. Basically, is there a Crystal reports-like equivalent for Django/Python?</p>
9
2009-07-06T19:11:27Z
1,088,974
<p>There is a grid on djangopackages.com which may be of use evaluating options:</p> <p><a href="https://www.djangopackages.com/grids/g/reporting/" rel="nofollow">https://www.djangopackages.com/grids/g/reporting/</a></p>
5
2009-07-06T20:07:55Z
[ "python", "django", "reporting" ]
Django Reporting Options
1,088,738
<p>I want to create a new "Business" application using the Django framework. Any suggestions as to what I can use as a reporting framework? The application will need to generate reports on various business entities including summaries, totals, grouping, etc. Basically, is there a Crystal reports-like equivalent for Django/Python?</p>
9
2009-07-06T19:11:27Z
1,092,513
<p><strong>Edit</strong> It really looks like both packages are gone, but now we have a nice data structure, borrowed from R -- <a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe" rel="nofollow">DataFrame</a> in pandas package <a href="http://gregreda.com/2013/10/26/working-with-pandas-dataframes" rel="nofollow">Quick tutorial</a> (pay attention to section "Grouping") </p> <hr> <p>I don't know about complete reporting solution for Django (or Python), but make reporting with Django is quite easy with or without ORM:</p> <ul> <li>django-tables can give you very basic structure for handling table data (asc/desc server-side sorting etc)</li> <li>you can use standart django 1.1 queryset aggregates (django-reporting uses them) for totals/subtotals stuff.</li> </ul> <p>Personally I use django-tables and neithere's <a href="http://bitbucket.org/neithere/datashaping/" rel="nofollow">datashaping</a> python package for quick summary/avg/median/IQR/filtering stuff because I have many different data sources (REST data, two mysql dbs, csv files from R) with only few of them in django db now.</p> <p>Pycha is one of candidates for me to draw simple charts.</p> <p>I don't like client-side ajax-based grids etc for reporting, but you can use it with django templates too.</p>
0
2009-07-07T13:59:14Z
[ "python", "django", "reporting" ]
Django Reporting Options
1,088,738
<p>I want to create a new "Business" application using the Django framework. Any suggestions as to what I can use as a reporting framework? The application will need to generate reports on various business entities including summaries, totals, grouping, etc. Basically, is there a Crystal reports-like equivalent for Django/Python?</p>
9
2009-07-06T19:11:27Z
19,415,730
<p>I made <a href="https://github.com/burke-software/django-report-builder" rel="nofollow">django-report-builder</a>. It lets you build ORM queries with a gui and generate spreadsheet reports. It can't do templates, that would be a great feature to add though.</p>
4
2013-10-16T23:28:17Z
[ "python", "django", "reporting" ]
How to print output using python?
1,088,764
<p>When this .exe file runs it prints a screen full of information and I want to print a particular line out to the screen, here on line "6":</p> <pre><code> cmd = ' -a ' + str(a) + ' -b ' + str(b) + str(Output) process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] outputlist = outputstring.splitlines() Output = outputlist[5] print cmd </code></pre> <p>This works fine: <code>cmd = ' -a ' + str(a) + ' -b ' + str(b)</code> </p> <p>This doesn't work: <code>cmd = ' -a ' + str(a) + ' -b ' + str(b) + str(Output)</code> </p> <p>I get an error saying <code>Output</code> isn't defined. But when I cut and paste:</p> <pre><code> outputstring = process.communicate()[0] outputlist = outputstring.splitlines() Output = outputlist[5] </code></pre> <p>before the cmd statement it tells me the process isn't defined. <code>str(Output)</code> should be what is printed on line 6 when the .exe is ran.</p>
3
2009-07-06T19:17:08Z
1,088,783
<p>Like you said, a variable has to be declared before you can use it. Therefore when you call <code>str(Output)</code> ABOVE <code>Output = outputlist[5]</code>, Output doesn't exist yet. You need the actually call first:</p> <pre><code>cmd = ' -a ' + str(a) + ' -b ' + str(b) </code></pre> <p>then you can print the output of that command:</p> <pre><code>cmd_return = ' -a ' + str(a) + ' -b ' + str(b) + str(Output) </code></pre> <p>should be the line directly above <code>print cmd_return</code>.</p>
0
2009-07-06T19:21:55Z
[ "python" ]
How to print output using python?
1,088,764
<p>When this .exe file runs it prints a screen full of information and I want to print a particular line out to the screen, here on line "6":</p> <pre><code> cmd = ' -a ' + str(a) + ' -b ' + str(b) + str(Output) process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] outputlist = outputstring.splitlines() Output = outputlist[5] print cmd </code></pre> <p>This works fine: <code>cmd = ' -a ' + str(a) + ' -b ' + str(b)</code> </p> <p>This doesn't work: <code>cmd = ' -a ' + str(a) + ' -b ' + str(b) + str(Output)</code> </p> <p>I get an error saying <code>Output</code> isn't defined. But when I cut and paste:</p> <pre><code> outputstring = process.communicate()[0] outputlist = outputstring.splitlines() Output = outputlist[5] </code></pre> <p>before the cmd statement it tells me the process isn't defined. <code>str(Output)</code> should be what is printed on line 6 when the .exe is ran.</p>
3
2009-07-06T19:17:08Z
1,088,790
<p>You're trying to append the result of a call into the call itself. You have to run the command once without the <code>+ str(Output)</code> part to get the output in the first place.</p> <p>Think about it this way. Let's say I was adding some numbers together.</p> <pre><code> z = 5 + b b = z + 2 </code></pre> <p>I have to define either <code>z</code> or <code>b</code> before the statements, depending on the order of the two statements. I can't use a variable before I know what it is. You're doing the same thing, using the <code>Output</code> variable before you define it.</p>
5
2009-07-06T19:23:55Z
[ "python" ]
How to print output using python?
1,088,764
<p>When this .exe file runs it prints a screen full of information and I want to print a particular line out to the screen, here on line "6":</p> <pre><code> cmd = ' -a ' + str(a) + ' -b ' + str(b) + str(Output) process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] outputlist = outputstring.splitlines() Output = outputlist[5] print cmd </code></pre> <p>This works fine: <code>cmd = ' -a ' + str(a) + ' -b ' + str(b)</code> </p> <p>This doesn't work: <code>cmd = ' -a ' + str(a) + ' -b ' + str(b) + str(Output)</code> </p> <p>I get an error saying <code>Output</code> isn't defined. But when I cut and paste:</p> <pre><code> outputstring = process.communicate()[0] outputlist = outputstring.splitlines() Output = outputlist[5] </code></pre> <p>before the cmd statement it tells me the process isn't defined. <code>str(Output)</code> should be what is printed on line 6 when the .exe is ran.</p>
3
2009-07-06T19:17:08Z
1,088,818
<p>It's not supposed to be a "dance" to move things around. It's a matter of what's on the left side of the "=". If it's on the left side, it's getting created; if it's on the right side it's being used. </p> <p>As it is, your example can't work even a little bit because line one wants part of output, which isn't created until the end.</p> <p>The easiest way to understand this is to work backwards. You want to see as the final result?</p> <pre><code>print output[5] </code></pre> <p>Right? So to get there, you have to get this from a larger string, right?</p> <pre><code>output= outputstring.splitlines() print output[5] </code></pre> <p>So where did <code>outputstring</code> come from? It was from some subprocess.</p> <pre><code>outputstring = process.communicate()[0] output= outputstring.splitlines() print output[5] </code></pre> <p>So where did process come from? It was created by subprocess Popen</p> <pre><code>process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] output= outputstring.splitlines() print output[5] </code></pre> <p>So where did cmd come from? I can't tell. Your example doesn't make sense on what command is being executed.</p> <pre><code>cmd = ? process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] output= outputstring.splitlines() print output[5] </code></pre>
1
2009-07-06T19:30:42Z
[ "python" ]
How to print output using python?
1,088,764
<p>When this .exe file runs it prints a screen full of information and I want to print a particular line out to the screen, here on line "6":</p> <pre><code> cmd = ' -a ' + str(a) + ' -b ' + str(b) + str(Output) process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE) outputstring = process.communicate()[0] outputlist = outputstring.splitlines() Output = outputlist[5] print cmd </code></pre> <p>This works fine: <code>cmd = ' -a ' + str(a) + ' -b ' + str(b)</code> </p> <p>This doesn't work: <code>cmd = ' -a ' + str(a) + ' -b ' + str(b) + str(Output)</code> </p> <p>I get an error saying <code>Output</code> isn't defined. But when I cut and paste:</p> <pre><code> outputstring = process.communicate()[0] outputlist = outputstring.splitlines() Output = outputlist[5] </code></pre> <p>before the cmd statement it tells me the process isn't defined. <code>str(Output)</code> should be what is printed on line 6 when the .exe is ran.</p>
3
2009-07-06T19:17:08Z
1,088,828
<p>Just change your first line to:</p> <p>cmd = ' -a ' + str(a) + ' -b ' + str(b)</p> <p>and the print statement at the end to:</p> <p>print cmd + str(Output)</p> <p>This is without knowing exactly what it is you want to print... It -seems- as if your problem is trying to use Output before you actually define what the Output variable is (as the posts above)</p>
1
2009-07-06T19:33:26Z
[ "python" ]