Re: extending PATH on Windows?

2016-02-20 Thread eryk sun
On Fri, Feb 19, 2016 at 6:57 PM, Dennis Lee Bieber
 wrote:
>
> Problem -- if the OP's PATH had contained the location of the add2path
> script, the OP might not have needed to search for it... (presuming their
> configuration also was set up to treat .py files as executable, entering
> win_add2path would be all that was needed to run it on a command line)

Ulli didn't need to run the file, but to read it as example code.

> "where" only searches the locations defined in PATH

I made it clear in several examples that where.exe is not limited to
searching PATH.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-19 Thread eryk sun
On Fri, Feb 19, 2016 at 8:18 AM, Gisle Vanem  wrote:
> Dennis Lee Bieber wrote:
>
 How can one search for files with DOS?
>>>
>>> dir /s /b \*add2path.*
>>>
>>> ChrisA
>>
>>   Or move to PowerShell...
>>
>> Windows PowerShell
>> Copyright (C) 2009 Microsoft Corporation. All rights reserved.
>>
>> PS C:\Users\Wulfraed\Documents> Get-ChildItem -Path c:\ -Filter *add2path*
>> -Name -Recurse
>
> Clumsy IMHO. Try:
> c:\> envtool --path *ipython*
>
> Matches in %PATH:

Your tool has special integration with Python's search paths, which is
cool. But for someone that wants some of these features without
installing another program and without learning PowerShell, where.exe
may suffice:

https://technet.microsoft.com/en-us/library/cc753148

Search PATH and the current directory:

C:\>where kd
C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\kd.exe

Search an environment variable that may contain one or more directories:

C:\>set MYPATH=^
More? %SystemRoot%\System32;^
More? %SystemRoot%\System32\drivers

C:\>where $MYPATH:conhost*.*
C:\Windows\System32\conhost.exe
C:\Windows\System32\ConhostV1.dll
C:\Windows\System32\ConhostV2.dll

Search a list of directories:

C:\>where "%MYPATH%":con*.sys
C:\Windows\System32\drivers\condrv.sys

Recursively search a directory:

C:\>where /r "%LocalAppData%\Programs" python.exe
C:\Users\Administrator\AppData\Local\Programs\Python\
Python35-32\python.exe
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-19 Thread eryk sun
On Thu, Feb 18, 2016 at 10:55 AM, Ulli Horlacher
 wrote:
> Ulli Horlacher  wrote:
>
>> > but simpler still and more reliable to just call QueryValueEx.
>>
>> I find it more complicated.
>
> I have now (after long studying docs and examples)::
>
> def get_winreg(key,subkey):
>   try:
> rkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER,key,0,winreg.KEY_READ)
> rvalue,rtype = winreg.QueryValueEx(rkey,subkey)
> winreg.CloseKey(rkey)
>   except WindowsError:
> rvalue,rtype = None,None
>   return rvalue

The 2nd parameter should be named "value_name", not "subkey".

A registry key is similar to an NTFS file-system node, and values are
similar to NTFS $DATA streams [1], but with different types of data
[2] other than just REG_BINARY, to make it easier to store structured
configuration data.

[1]: https://msdn.microsoft.com/en-us/library/aa364404
[2]: https://msdn.microsoft.com/en-us/library/ms724884
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-19 Thread eryk sun
On Fri, Feb 19, 2016 at 4:48 AM, Chris Angelico  wrote:
> On Fri, Feb 19, 2016 at 9:42 PM, Ulli Horlacher
>  wrote:
>> pyotr filipivich  wrote:
>>
>>> >   Windows (especially 7) search function is highly crippled. There is
>>> >some command sequence that will open it up to looking at other file types
>>> >and locations.
>>> >
>>> >http://answers.microsoft.com/en-us/windows/forum/windows_7-files/windows-7-search-does-not-find-files-that-it/61b88d5e-7df7-4427-8a2e-82b801a4a746?auth=1
>>>
>>>
>>> Thanks.  I've found it "simpler" to just open a command prompt, and
>>> use DOS.
>>
>> How can one search for files with DOS?
>
> dir /s /b \*add2path.*

This search is carried out by Windows NT instead of MS-DOS in almost
all cases nowadays:

Z:\Python\repo\2.7>dir /s /b Tools\Scripts\win_add?*.*
Breakpoint 0 hit
ntdll!NtQueryDirectoryFile:
7ffb`d9d138c0 4c8bd1  mov r10,rcx

0:000> dS poi(@rsp + a*8)
00df`bab1ff9a  "win_add><"*"

NT has normal (i.e. sane) * and ? wildcard matching, so WinAPI
FindFirstFile has to translate DOS wildcards to special values before
calling NtQueryDirectoryFile. See the file-system runtime library
function FsRtlIsNameInExpression [1]. Dot, question mark, and asterisk
may be mapped (depending on context in the string) to double quote and
the angle brackets, as shown in the above debugger output in which
'win_add?*.*' is passed to the system call as 'win_add><"*'.

DOS_DOT (")
Matches either a period or zero characters beyond the
name string.

DOS_QM (>)
Matches any single character or, upon encountering a
period or end of name string, advances the expression
to the end of the set of contiguous DOS_QMs.

DOS_STAR (<)
Matches zero or more characters until encountering
and matching the final . in the name.

[1]: https://msdn.microsoft.com/en-us/library/ff546850
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-19 Thread pyotr filipivich
Ulli Horlacher  on Fri, 19 Feb 2016
10:42:52 + (UTC) typed in comp.lang.python  the following:
>pyotr filipivich  wrote:
>
>> >   Windows (especially 7) search function is highly crippled. There is
>> >some command sequence that will open it up to looking at other file types
>> >and locations.
>> >
>> >http://answers.microsoft.com/en-us/windows/forum/windows_7-files/windows-7-search-does-not-find-files-that-it/61b88d5e-7df7-4427-8a2e-82b801a4a746?auth=1
>> 
>> 
>> Thanks.  I've found it "simpler" to just open a command prompt, and
>> use DOS.
>
>How can one search for files with DOS?

cd %searchPathStart%
dir /s *.php
or variants.
-- 
pyotr filipivich
Next month's Panel: Graft - Boon or blessing?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-19 Thread Gisle Vanem
Dennis Lee Bieber wrote:

>>> How can one search for files with DOS?
>>
>> dir /s /b \*add2path.*
>>
>> ChrisA
>
>   Or move to PowerShell...
>
> Windows PowerShell
> Copyright (C) 2009 Microsoft Corporation. All rights reserved.
>
> PS C:\Users\Wulfraed\Documents> Get-ChildItem -Path c:\ -Filter *add2path*
> -Name -Recurse

Clumsy IMHO. Try:
c:\> envtool --path *ipython*

Matches in %PATH:
  12 Feb 2015 - 17:16:12: f:\ProgramFiler\Python27\Scripts\ipython-script.py
  12 Feb 2015 - 17:16:12: f:\ProgramFiler\Python27\Scripts\ipython.exe
  12 Feb 2015 - 17:16:12: 
f:\ProgramFiler\Python27\Scripts\ipython.exe.manifest
  12 Feb 2015 - 17:16:12: 
f:\ProgramFiler\Python27\Scripts\ipython2-script.py
  12 Feb 2015 - 17:16:12: f:\ProgramFiler\Python27\Scripts\ipython2.exe
  12 Feb 2015 - 17:16:12: 
f:\ProgramFiler\Python27\Scripts\ipython2.exe.manifest
  08 Feb 2015 - 12:48:56: 
f:\ProgramFiler\Python27\Scripts\ipython_win_post_install.py
7 matches found for "*ipython*".

---

Or find a spec on *all partitions* using Everything Search engine:
c:\> envtool --evry *ipython*
Matches from EveryThing:
...
133 matches found for "*ipython*".

---

Or for Python-path searches:
c:\> envtool --python *ipython*
Matches in "f:\ProgramFiler\Python27\python.exe" sys.path[]:
  23 Jan 2016 - 13:50:30: 
f:\ProgramFiler\Python27\lib\site-packages\ipython-2.1.0-py2.7.egg\IPython\
  23 Jan 2016 - 13:50:26: 
f:\ProgramFiler\Python27\lib\site-packages\IPython\
  23 Jan 2016 - 13:50:30: 
f:\ProgramFiler\Python27\lib\site-packages\ipython-2.1.0-py2.7.egg\
3 matches found for "*ipython*".

-

My envtool is at https://github.com/gvanem/EnvTool
EveryThing is at http://voidtools.com/

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-19 Thread Chris Angelico
On Fri, Feb 19, 2016 at 9:42 PM, Ulli Horlacher
 wrote:
> pyotr filipivich  wrote:
>
>> >   Windows (especially 7) search function is highly crippled. There is
>> >some command sequence that will open it up to looking at other file types
>> >and locations.
>> >
>> >http://answers.microsoft.com/en-us/windows/forum/windows_7-files/windows-7-search-does-not-find-files-that-it/61b88d5e-7df7-4427-8a2e-82b801a4a746?auth=1
>>
>>
>> Thanks.  I've found it "simpler" to just open a command prompt, and
>> use DOS.
>
> How can one search for files with DOS?

dir /s /b \*add2path.*

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-19 Thread Ulli Horlacher
pyotr filipivich  wrote:

> >   Windows (especially 7) search function is highly crippled. There is
> >some command sequence that will open it up to looking at other file types
> >and locations.
> >
> >http://answers.microsoft.com/en-us/windows/forum/windows_7-files/windows-7-search-does-not-find-files-that-it/61b88d5e-7df7-4427-8a2e-82b801a4a746?auth=1
> 
> 
> Thanks.  I've found it "simpler" to just open a command prompt, and
> use DOS.

How can one search for files with DOS?

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-18 Thread pyotr filipivich
Dennis Lee Bieber  on Thu, 18 Feb 2016 21:57:13
-0500 typed in comp.lang.python  the following:
>On Thu, 18 Feb 2016 16:24:00 + (UTC), Ulli Horlacher
> declaimed the following:
>
>>Dennis Lee Bieber  wrote:
>>
>>> >I have 
>>> >"Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC
>>> >v.1500 32 bit (Intel)] on win32"
>>> >and there is no "win_add2path.py"
>>> >
>>> C:\Python_x64\Python27\Tools\scripts\win_add2path.py
>>
>>Ok, It is here in C:\Python27\Tools\scripts\win_add2path.py
>>but windows "Search programs and files" was not able to find it.
>
>   Windows (especially 7) search function is highly crippled. There is
>some command sequence that will open it up to looking at other file types
>and locations.
>
>http://answers.microsoft.com/en-us/windows/forum/windows_7-files/windows-7-search-does-not-find-files-that-it/61b88d5e-7df7-4427-8a2e-82b801a4a746?auth=1


Thanks.  I've found it "simpler" to just open a command prompt, and
use DOS.
-- 
pyotr filipivich
Next month's Panel: Graft - Boon or blessing?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-18 Thread Ulli Horlacher
Ulli Horlacher  wrote:

> > but simpler still and more reliable to just call QueryValueEx.
> 
> I find it more complicated.

I have now (after long studying docs and examples)::

def get_winreg(key,subkey):
  try:
rkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER,key,0,winreg.KEY_READ)
rvalue,rtype = winreg.QueryValueEx(rkey,subkey)
winreg.CloseKey(rkey)
  except WindowsError:
rvalue,rtype = None,None
  return rvalue


def set_winreg(key,subkey,value):
  winreg.CreateKey(winreg.HKEY_CURRENT_USER,key)
  rkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER,key,0,winreg.KEY_WRITE)
  winreg.SetValueEx(rkey,subkey,0,winreg.REG_SZ,value)
  winreg.CloseKey(rkey)

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-18 Thread Ulli Horlacher
eryk sun  wrote:


> https://hg.python.org/cpython/file/v2.7.11/Tools/scripts/win_add2path.py
> 
> But there are a few issues with this script.

(... lot of flaws ...)

> Here's a new version for Python 2. I generalized the shell-variable
> replacement to a list of well-known folders.

Great script, I will save it for later usage!

But in the meantime I came to another solution:
Instead of modifying PATH systemwide, I modify it only for cmd.exe.

To achieve this, I set the registry key
"HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun"
to "%USERPROFILE%\autorun.cmd" and write in this file:
set PATH=%PATH%;%USERPROFILE%\Desktop

If there was already an old value in
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
it will be saved to %USERPROFILE%\autorun.cmd, too

This autorun.cmd is like .bashrc on UNIX.

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-18 Thread Ulli Horlacher
Dennis Lee Bieber  wrote:

> >I have 
> >"Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC
> >v.1500 32 bit (Intel)] on win32"
> >and there is no "win_add2path.py"
> >
> C:\Python_x64\Python27\Tools\scripts\win_add2path.py

Ok, It is here in C:\Python27\Tools\scripts\win_add2path.py
but windows "Search programs and files" was not able to find it.

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-18 Thread eryk sun
On Wed, Feb 17, 2016 at 6:53 PM, Dennis Lee Bieber
 wrote:
> On Wed, 17 Feb 2016 17:49:11 + (UTC), Ulli Horlacher
>  declaimed the following:
>
>>Thorsten Kampe  wrote:
>>
>>> By the way: there is a script called `win_add2path.py` in your Python
>>> distribution
>>
>>I have
>>"Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC
>>v.1500 32 bit (Intel)] on win32"
>>and there is no "win_add2path.py"
>>
> C:\Python_x64\Python27\Tools\scripts\win_add2path.py
>
> PythonWin 2.7.5 (default, Sep 16 2013, 23:11:01) [MSC v.1500 64 bit
> (AMD64)] on win32.
> Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for
> further copyright information.
>
> But I can't confirm that this is not something added in the ActiveState
> release.

It's here:
https://hg.python.org/cpython/file/v2.7.11/Tools/scripts/win_add2path.py

But there are a few issues with this script.

* A default value of u"%PATH%" is wrong. That causes the system
  PATH to be concatenated with itself.

* For the user scripts directory, replacing appdata with
  "%APPDATA%" causes os.path.isdir to always fail.

* For QueryValueEx, the only error it should handle is
  ERROR_FILE_NOT_FOUND. Other OS errors are unlikely, but they
  shouldn't be masked.

* In Python 2, the value returned by QueryValueEx is a unicode
  string, which this script assumes is ASCII only. So it could
  die on a UnicodeDecodeError.

* REG_EXPAND_SZ should only be used when '%' occurs 2 or more
  times. Otherwise use REG_SZ. This is important for two-pass
  environment variable expansion. Thus an existing REG_SZ type
  should be preserved, if that's reasonable, because the user may be
  reusing PATH in a  REG_EXPAND_SZ variable.

* It doesn't broadcast a WM_SETTINGCHANGE message, so it
  needlessly forces the user to log off and back on in order to
  use the modified PATH.

Here's a new version for Python 2. I generalized the shell-variable
replacement to a list of well-known folders.

import os
import sys
import site
import ctypes
import _winreg
import warnings

user32 = ctypes.WinDLL('user32', use_last_error=True)

HWND_BROADCAST = 0x
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
ERROR_FILE_NOT_FOUND = 0x0002
ERROR_TIMEOUT = 0x05B4
HKCU = _winreg.HKEY_CURRENT_USER

ENVIRONMENT = u"Environment"
PATH = u"PATH"
SCRIPTS = u"Scripts"

dir_vars = [u"%APPDATA%",
u"%LOCALAPPDATA%",
u"%USERPROFILE%",
u"%HOMEDRIVE%%HOMEPATH%",
u"%ProgramFiles%",
u"%ProgramFiles(x86)%"]

dir_vals = [_winreg.ExpandEnvironmentStrings(v) for v in dir_vars]

def broadcast_change(lparam):
if not user32.SendMessageTimeoutW(
HWND_BROADCAST, WM_SETTINGCHANGE,
0, ctypes.c_wchar_p(lparam),
SMTO_ABORTIFHUNG, 1000, None):
err = ctypes.get_last_error()
if err != ERROR_TIMEOUT:
raise ctypes.WinError(err)

def modify():
executable = sys.executable.decode("mbcs")
pythonpath = os.path.dirname(os.path.normpath(executable))
scripts = os.path.join(pythonpath, SCRIPTS)
if hasattr(site, "USER_SITE"):
userpath = site.USER_SITE.decode("mbcs")
userscripts = os.path.join(userpath, SCRIPTS)
else:
userscripts = None
with _winreg.CreateKey(HKCU, ENVIRONMENT) as key:
try:
envpath, dtype = _winreg.QueryValueEx(key, PATH)
except WindowsError as e:
if e.winerror != ERROR_FILE_NOT_FOUND:
raise
envpath, dtype = u"", _winreg.REG_EXPAND_SZ
if dtype not in (_winreg.REG_SZ, _winreg.REG_EXPAND_SZ):
raise TypeError(r"Existing PATH value is not a string.")
if dtype == _winreg.REG_SZ and envpath.count(u"%") > 1:
warnings.warn('Changing type to REG_EXPAND_SZ.')
dtype = _winreg.REG_EXPAND_SZ
paths = [envpath]
for path in (pythonpath, scripts, userscripts):
if path and path not in envpath and os.path.isdir(path):
if dtype == _winreg.REG_EXPAND_SZ:
for var, val in zip(dir_vars, dir_vals):
if val in path:
path = path.replace(val, var)
break
if path in envpath:
continue
paths.append(path)
envpath = os.pathsep.join(paths)
_winreg.SetValueEx(key, PATH, 0, dtype, envpath)
broadcast_change(ENVIRONMENT)
return paths, envpath

def main():
paths, envpath = modify()
if len(paths) > 1:
print "Path(s) added:"
 

Re: extending PATH on Windows?

2016-02-17 Thread Ulli Horlacher
eryk sun  wrote:

> >> The AutoRun command (it's a command line, not a script path)
> >
> > A script path is a legal command line, too.
> 
> If the registry value were just a script path, you'd have to modify
> your script to chain to the previous script, if any. Since it's a
> command line you can simply use the & operator to append another
> command.

This is the better way, no question. I will change it.


> Do you really intend for your batch file to be run every time cmd.exe
> is executed, including every time that every program on the machine
> calls the CRT system() function?

Yes. It just extends PATH, it should not do any harm.


> Why don't you just install a shortcut to a batch file that starts a
> command prompt with the extended PATH?

Hmm... how does a user starts this shortcut, when it is not found in PATH?


> system('reg...') won't be able to do that unless you export the key to
> a .reg file and parse the existing AutoRun value. It would be simpler
> to use subprocess.check_output('reg query ...')

I do it this way, already.


> but simpler still and more reliable to just call QueryValueEx.

I find it more complicated.

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-17 Thread eryk sun
On Wed, Feb 17, 2016 at 2:29 PM, Ulli Horlacher
 wrote:
> eryk sun  wrote:
>> >
>> > set PATH=%PATH%;%USERPROFILE%\Desktop
>>
>> The AutoRun command (it's a command line, not a script path)
>
> A script path is a legal command line, too.

If the registry value were just a script path, you'd have to modify
your script to chain to the previous script, if any. Since it's a
command line you can simply use the & operator to append another
command.

>> gets run for every instance of cmd.exe
>
> Yes, this is the intended trick!

Do you really intend for your batch file to be run every time cmd.exe
is executed, including every time that every program on the machine
calls the CRT system() function?

Why don't you just install a shortcut to a batch file that starts a
command prompt with the extended PATH?

>> Also, you can't just overwrite a user's AutoRun command like that. If
>> a command currently exists, you have to concatenate your command with
>> the existing command using parentheses and the "&" operator, e.g.
>> (previous_command) & (your_command).
>
> Good hint, thanks!
>
>> Use winreg for this.
>
> system("reg ...") works for me and is easier :-)

system('reg...') won't be able to do that unless you export the key to
a .reg file and parse the existing AutoRun value. It would be simpler
to use subprocess.check_output('reg query ...'), but simpler still and
more reliable to just call QueryValueEx.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-17 Thread Ulli Horlacher
eryk sun  wrote:

> > At startup cmd.exe runs a script which is defined by the registry variable
> > AutoRun in "HKCU\Software\Microsoft\Command Processor"
> >
> > I set this variable with:
> >
> >   rc = "HKCU\Software\Microsoft\Command Processor"
> >   ar = "%USERPROFILE%\Desktop\autorun.cmd"
> >   system('reg add "%s" /v AutoRun /d "%s"' % (rc,ar))
> >
> > and write into autorun.cmd:
> >
> > set PATH=%PATH%;%USERPROFILE%\Desktop
> 
> The AutoRun command (it's a command line, not a script path)

A script path is a legal command line, too.


> gets run for every instance of cmd.exe

Yes, this is the intended trick!


> Your batch file needs to set a sentinel variable such as YOUR_APP_AUTORUN
> that, if set, makes the batch file exit without extending PATH if it was
> already done.

Having "%USERPROFILE%\Desktop" twice in PATH is not a problem.


> Also, you can't just overwrite a user's AutoRun command like that. If
> a command currently exists, you have to concatenate your command with
> the existing command using parentheses and the "&" operator, e.g.
> (previous_command) & (your_command).

Good hint, thanks!


> Use winreg for this.

system("reg ...") works for me and is easier :-)

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-17 Thread eryk sun
On Wed, Feb 17, 2016 at 11:49 AM, Ulli Horlacher
 wrote:
> At startup cmd.exe runs a script which is defined by the registry variable
> AutoRun in "HKCU\Software\Microsoft\Command Processor"
>
> I set this variable with:
>
>   rc = "HKCU\Software\Microsoft\Command Processor"
>   ar = "%USERPROFILE%\Desktop\autorun.cmd"
>   system('reg add "%s" /v AutoRun /d "%s"' % (rc,ar))
>
> and write into autorun.cmd:
>
> set PATH=%PATH%;%USERPROFILE%\Desktop

The AutoRun command (it's a command line, not a script path) gets run
for every instance of cmd.exe, unless cmd is started with the /D
option. This includes the CRT's system() function. Your batch file
needs to set a sentinel variable such as YOUR_APP_AUTORUN that, if
set, makes the batch file exit without extending PATH if it was
already done.

Also, you can't just overwrite a user's AutoRun command like that. If
a command currently exists, you have to concatenate your command with
the existing command using parentheses and the "&" operator, e.g.
(previous_command) & (your_command). Use winreg for this.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-17 Thread Ulli Horlacher
Thorsten Kampe  wrote:

> By the way: there is a script called `win_add2path.py` in your Python 
> distribution

I have 
"Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC
v.1500 32 bit (Intel)] on win32"
and there is no "win_add2path.py"

But I found another solution:

I need the extended PATH only for cmd.exe: users shall run my program
(a compiled executable) without having to enter the full path.

At startup cmd.exe runs a script which is defined by the registry variable
AutoRun in "HKCU\Software\Microsoft\Command Processor"

I set this variable with:

  rc = "HKCU\Software\Microsoft\Command Processor"
  ar = "%USERPROFILE%\Desktop\autorun.cmd"
  system('reg add "%s" /v AutoRun /d "%s"' % (rc,ar))

and write into autorun.cmd:

set PATH=%PATH%;%USERPROFILE%\Desktop


This command extends PATH only for this cmd.exe instance.
This is all I need!


-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-16 Thread Thorsten Kampe
* Ulli Horlacher (Tue, 16 Feb 2016 12:38:44 + (UTC))

By the way: there is a script called `win_add2path.py` in your Python 
distribution which "is a simple script to add Python to the Windows 
search path. It modifies the current user (HKCU) tree of the 
registry.". That should do most of what you want.

Thorsten

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-16 Thread Thorsten Kampe
* Ulli Horlacher (Tue, 16 Feb 2016 12:38:44 + (UTC))
> 
> Thorsten Kampe  wrote:
> > * Ulli Horlacher (Tue, 16 Feb 2016 08:30:59 + (UTC))
> > > I need to extend the PATH environment variable on Windows.
> > 
> > 1. Add the path component yourself into HKEY_CURRENT_USER and make 
> > sure it's not there already (pure Python).
> 
> Preferred!
> What is HKEY_CURRENT_USER? Another environment variable?

It's a hive in the Windows registry and the equivalent of `~/.*` in 
Linux terms (HKEY_LOCAL_MACHINE[/Software] being the equivalent of 
`/etc`). The fact that you're asking indicates that you should read 
about that in advance. 

The task itself is definitely not that hard. Maybe someone has 
already asked at StackOverflow. But the devil's in the detail.

Some things to consider

- Python is not by default installed on Windows, so you have to use a 
way to run your script without (PyInstaller for instance).

- by default there is no entry in HKCU, so you have to create it 
first (under HKEY_CURRENT_USER\Environment).

- you need to create the correct type (REG_SZ, null-terminated 
string)

- Windows paths are semicolon separated (not colon).

- Windows only module for the Registry: 
https://docs.python.org/3/library/winreg.html

Thorsten

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-16 Thread eryk sun
On Tue, Feb 16, 2016 at 2:30 AM, Ulli Horlacher
 wrote:
>
> So far, I use:
>
>system('setx PATH "%PATH%;'+bindir+'"')
>
> The problem: In a new process (cmd.exe) PATH contains a lot of double
> elements. As far as I have understood, Windows builds the PATH
> environment variable from a system component and a user component. With
> the setx command from above I have copied the system PATH into the user
> PATH component.

setx broadcasts a WM_SETTINGCHANGE [1] message that notifies Explorer
to reload its environment from the registry, so the user doesn't have
to start a new session. It also decides whether to use REG_SZ or
REG_EXPAND_SZ depending on the presence of mutliple "%" characters in
the string.

[1]: https://msdn.microsoft.com/en-us/library/ms725497

But as you note it's no good for extending an existing value,
especially not for PATH or a value that references other "%variables%"
that you want to remain unexpanded. To do this right, you have to at
least use winreg to query the user's PATH value from the registry. But
then you may as well replace setx completely. Here's a little
something to get you started.

import os
import sys
import types
import ctypes

user32 = ctypes.WinDLL('user32', use_last_error=True)

try:
import winreg
except ImportError:
import _winreg as winreg

def extend_path(new_paths, persist=True):
if isinstance(new_paths, getattr(types, 'StringTypes', str)):
new_paths = [new_paths]
new_paths = [os.path.abspath(p) for p in new_paths]
paths = [p for p in os.environ.get('PATH', '').split(os.pathsep) if p]
for p in new_paths:
if p not in paths:
paths.append(p)
os.environ['PATH'] = os.pathsep.join(paths)
if persist:
_persist_path(new_paths)

def _persist_path(new_paths):
if sys.version_info[0] == 2:
temp_paths = []
for p in new_paths:
if isinstance(p, unicode):
temp_paths.append(p)
else:
temp_paths.append(p.decode('mbcs'))
new_paths = temp_paths
with winreg.OpenKey(winreg.HKEY_CURRENT_USER,
'Environment', 0,
winreg.KEY_QUERY_VALUE |
winreg.KEY_SET_VALUE) as hkey:
try:
user_path, dtype = winreg.QueryValueEx(hkey, 'PATH')
except WindowsError as e:
ERROR_FILE_NOT_FOUND = 0x0002
if e.winerror != ERROR_FILE_NOT_FOUND:
raise
paths = []
else:
if dtype in (winreg.REG_SZ, winreg.REG_EXPAND_SZ):
paths = [p for p in user_path.split(os.pathsep) if p]
else:
paths = []
for p in new_paths:
if p not in paths:
paths.append(p)
pathstr = os.pathsep.join(paths)
if pathstr.count('%') < 2:
dtype = winreg.REG_SZ
else:
dtype = winreg.REG_EXPAND_SZ
winreg.SetValueEx(hkey, 'PATH', 0, dtype, pathstr)
_broadcast_change(u'Environment')

def _broadcast_change(lparam):
HWND_BROADCAST   = 0x
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 0x0002
ERROR_TIMEOUT = 0x05B4
wparam = 0
if not user32.SendMessageTimeoutW(
HWND_BROADCAST, WM_SETTINGCHANGE,
wparam, ctypes.c_wchar_p(lparam),
SMTO_ABORTIFHUNG, 1000, None):
err = ctypes.get_last_error()
if err != ERROR_TIMEOUT:
raise ctypes.WinError(err)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-16 Thread Ulli Horlacher
Thorsten Kampe  wrote:
> * Ulli Horlacher (Tue, 16 Feb 2016 08:30:59 + (UTC))
> > I need to extend the PATH environment variable on Windows.
> 
> 1. Add the path component yourself into HKEY_CURRENT_USER and make 
> sure it's not there already (pure Python).

Preferred!
What is HKEY_CURRENT_USER? Another environment variable?

-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: extending PATH on Windows?

2016-02-16 Thread Thorsten Kampe
* Ulli Horlacher (Tue, 16 Feb 2016 08:30:59 + (UTC))
> I need to extend the PATH environment variable on Windows.
> 
> So far, I use:
> 
>system('setx PATH "%PATH%;'+bindir+'"')
> 
> The problem: In a new process (cmd.exe) PATH contains a lot of double
> elements. As far as I have understood, Windows builds the PATH
> environment variable from a system component and a user component. With
> the setx command from above I have copied the system PATH into the user
> PATH component.
> 
> Is there a better way to extend the PATH environment variable for the user?
> It must be persistent, not only for the current process.

`os.system` should be `subprocess.call` on modern systems (actually 
`subprocess.run` if you have Python 3.5). Since `setx` doesn't seem 
to have unique and add options, you basically have two options:

1. Add the path component yourself into HKEY_CURRENT_USER and make 
sure it's not there already (pure Python).

2. a) use a shell that offers that capability with `set`: 
https://jpsoft.com/help/set.htm (TCC/LE is free)

   b) use a dedicated environment variable editor: 
http://www.rapidee.com/en/command-line

Thorsten

-- 
https://mail.python.org/mailman/listinfo/python-list


extending PATH on Windows?

2016-02-16 Thread Ulli Horlacher
I need to extend the PATH environment variable on Windows.

So far, I use:

   system('setx PATH "%PATH%;'+bindir+'"')

The problem: In a new process (cmd.exe) PATH contains a lot of double
elements. As far as I have understood, Windows builds the PATH
environment variable from a system component and a user component. With
the setx command from above I have copied the system PATH into the user
PATH component.

Is there a better way to extend the PATH environment variable for the user?
It must be persistent, not only for the current process.


-- 
Ullrich Horlacher  Server und Virtualisierung
Rechenzentrum IZUS/TIK E-Mail: horlac...@tik.uni-stuttgart.de
Universitaet Stuttgart Tel:++49-711-68565868
Allmandring 30aFax:++49-711-682357
70550 Stuttgart (Germany)  WWW:http://www.tik.uni-stuttgart.de/
-- 
https://mail.python.org/mailman/listinfo/python-list