How to get path of Start Menu's Programs directory? - python

...for current user? for all users?
I'm working an a small program which needs to create links in the start menu. Currently I'm hardcoding like below, but it only works in english locales, for example it should be "Startmenü" in german. What are cleaner, more portable approaches?
OUR_STARTMENU = os.environ['ALLUSERSPROFILE'] + '\Start Menu\Programs\Our Stuff'
thank you

I've heard of 2 ways of doing this. First:
from win32com.shell import shell
shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_COMMON_STARTMENU)
Second, using the WScript.Shell object (source : http://www.mail-archive.com/python-win32#python.org/msg00992.html):
import win32com.client
objShell = win32com.client.Dispatch("WScript.Shell")
allUserProgramsMenu = objShell.SpecialFolders("AllUsersPrograms")
userMenu = objShell.SpecialFolders("StartMenu")
Another source: http://blogs.msdn.com/saveenr/archive/2005/12/28/creating-a-start-menu-shortcut-with-powershell-and-python.aspx

Also, CSIDL_COMMON_STARTMENU is for all user startup and CSIDL_STARTMENU for current user startup.

A friend, Luke Pinner of Environment.gov.au, gave a solution by email which uses a core module (python 2.5+). Believed to be multi-lingual as the return from the API call is unicode. Tested on Win7 with Japanese locale, and on another us-english machine by manually changing Start Menu to point to %USERPROFILE%\Startmenü
''' Get windows special folders without pythonwin
Example:
import specialfolders
start_programs = specialfolders.get(specialfolders.PROGRAMS)
Code is public domain, do with it what you will.
Luke Pinner - Environment.gov.au, 2010 February 10
'''
#Imports use _syntax to mask them from autocomplete IDE's
import ctypes as _ctypes
from ctypes.wintypes import HWND as _HWND, HANDLE as _HANDLE,DWORD as _DWORD,LPCWSTR as _LPCWSTR,MAX_PATH as _MAX_PATH, create_unicode_buffer as _cub
_SHGetFolderPath = _ctypes.windll.shell32.SHGetFolderPathW
#public special folder constants
DESKTOP= 0
PROGRAMS= 2
MYDOCUMENTS= 5
FAVORITES= 6
STARTUP= 7
RECENT= 8
SENDTO= 9
STARTMENU= 11
MYMUSIC= 13
MYVIDEOS= 14
NETHOOD= 19
FONTS= 20
TEMPLATES= 21
ALLUSERSSTARTMENU= 22
ALLUSERSPROGRAMS= 23
ALLUSERSSTARTUP= 24
ALLUSERSDESKTOP= 25
APPLICATIONDATA= 26
PRINTHOOD= 27
LOCALSETTINGSAPPLICATIONDATA= 28
ALLUSERSFAVORITES= 31
LOCALSETTINGSTEMPORARYINTERNETFILES=32
COOKIES= 33
LOCALSETTINGSHISTORY= 34
ALLUSERSAPPLICATIONDATA= 35
def get(intFolder):
_SHGetFolderPath.argtypes = [_HWND, _ctypes.c_int, _HANDLE, _DWORD, _LPCWSTR]
auPathBuffer = _cub(_MAX_PATH)
exit_code=_SHGetFolderPath(0, intFolder, 0, 0, auPathBuffer)
return auPathBuffer.value

Related

nglview installed but will not import inside Juypter Notebook via Anaconda.Navigator

I'm having trouble importing nglview inside a Juypter Notebook (JNb) cell. The instance of JNb is started via the base (root) Environment inside Anaconda.Navigator GUI. Inside Anaconda.Navigator, I've installed nglview. But the import continues to fail.
Versions:
Jupyter Notebook (inside Anaconda.Navigator) - 6.4.12
Anaconda.Navigator (GUI) - 2.3.2
Python - 3.9
nglview - 3.0.3 (installed but not importing)
ipython 8.5.0
This is the error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [1], line 5
3 import pandas as pd
4 import matplotlib.pyplot as plt
----> 5 import nglview as nv
7 # the next line is necessary to display plots in Jupyter
8 get_ipython().run_line_magic('matplotlib', 'inline')
File ~\anaconda3\lib\site-packages\nglview\__init__.py:4
1 import warnings
3 # for doc
----> 4 from . import adaptor, datafiles, show, widget
5 from ._version import get_versions
6 from .adaptor import *
File ~\anaconda3\lib\site-packages\nglview\show.py:13
3 from . import datafiles
4 from .adaptor import (ASEStructure, ASETrajectory, BiopythonStructure,
5 FileStructure, HTMDTrajectory, IODataStructure,
6 IOTBXStructure, MDAnalysisTrajectory, MDTrajTrajectory,
(...)
11 RdkitStructure,
12 TextStructure)
---> 13 from .widget import NGLWidget
15 __all__ = [
16 'demo',
17 'show_pdbid',
(...)
40 'show_biopython',
41 ]
44 def show_pdbid(pdbid, **kwargs):
File ~\anaconda3\lib\site-packages\nglview\widget.py:19
15 from traitlets import (Bool, CaselessStrEnum, Dict, Instance, Int, Integer,
16 List, Unicode, observe, validate)
17 import traitlets
---> 19 from . import color, interpolate
20 from .adaptor import Structure, Trajectory
21 from .component import ComponentViewer
File ~\anaconda3\lib\site-packages\nglview\color.py:114
110 else:
111 raise ValueError(f"{obj} must be either list of list or string")
--> 114 ColormakerRegistry = _ColormakerRegistry()
File ~\anaconda3\lib\site-packages\nglview\base.py:10, in _singleton.<locals>.getinstance()
8 def getinstance():
9 if cls not in instances:
---> 10 instances[cls] = cls()
11 return instances[cls]
File ~\anaconda3\lib\site-packages\nglview\color.py:47, in _ColormakerRegistry.__init__(self, *args, **kwargs)
45 try:
46 get_ipython() # only display in notebook
---> 47 self._ipython_display_()
48 except NameError:
49 pass
File ~\anaconda3\lib\site-packages\nglview\color.py:54, in _ColormakerRegistry._ipython_display_(self, **kwargs)
52 if self._ready:
53 return
---> 54 super()._ipython_display_(**kwargs)
AttributeError: 'super' object has no attribute '_ipython_display_'
What is missing? I need to resolve this issue within the GUI of Anaconda.Navigator, as I need nglview as part of an exercise for students who do not have a background in computational sciences. I'm not after a solution that uses anything but the GUI. Asking a group over Zoom to start hacking around with a Mac/Windows/Linux terminal would be a nightmare. Many thanks.
UPDATE
Recent efforts have included:
closing and restarting Anaconda.Navigator GUI
"Quit" the Jupyter server (option found in the browser tab). Restarted the server.
%conda install -c conda-forge nglview at the top of the Notebook. It just informs me that it's already installed.
Closing the tab and all mentions of Anaconda and Jupyter (but not the browser window instance itself).
The fact that I haven't restarted the machine itself is a big grey elephant. Unfortunately, it's running a long Quantum chemistry calculation in the background that can't be continued after boot :-( Sorry. But I don't want to get hung up on restarting a machine - it shouldn't come down to that.
Check whether the version of ipywidget in your current conda version is above 8.0.0. Because Jupyter notebook is not compatible with the new version of ipywidget. Thus try the command below to install the older version of ipywidget, then ǹglview` should be properly imported:
conda install "ipywidgets <8" -c conda-forge

ModuleNotFoundError: No java install detected. Please install java to use language-tool-python

I would like to check the number if issues in a given sentence.
my code is
import language_tool_python
tl = language_tool_python.LanguageTool('en-US')
txt = "good mooorning sirr and medam my namee anderen i am from amerecia !"
m = tl.check(txt)
len(m)
Instead of returning the number i am getting error message as shown below.
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-1c4c9134d6f4> in <module>
1 import language_tool_python
----> 2 tool = language_tool_python.LanguageTool('en-US')
3
4 text = "Your the best but their are allso good !"
5 matches = tool.check(text)
E:\Anaconda\lib\site-packages\language_tool_python\server.py in __init__(self, language, motherTongue, remote_server, newSpellings, new_spellings_persist)
43 self._update_remote_server_config(self._url)
44 elif not self._server_is_alive():
---> 45 self._start_server_on_free_port()
46 if language is None:
47 try:
E:\Anaconda\lib\site-packages\language_tool_python\server.py in _start_server_on_free_port(self)
212 self._url = 'http://{}:{}/v2/'.format(self._HOST, self._port)
213 try:
--> 214 self._start_local_server()
215 break
216 except ServerError:
E:\Anaconda\lib\site-packages\language_tool_python\server.py in _start_local_server(self)
222 def _start_local_server(self):
223 # Before starting local server, download language tool if needed.
--> 224 download_lt()
225 err = None
226 try:
E:\Anaconda\lib\site-packages\language_tool_python\download_lt.py in download_lt(update)
142 ]
143
--> 144 confirm_java_compatibility()
145 version = LATEST_VERSION
146 filename = FILENAME.format(version=version)
E:\Anaconda\lib\site-packages\language_tool_python\download_lt.py in confirm_java_compatibility()
73 # found because of a PATHEXT-related issue
74 # (https://bugs.python.org/issue2200).
---> 75 raise ModuleNotFoundError('No java install detected. Please install java to use language-tool-python.')
76
77 output = subprocess.check_output([java_path, '-version'],
ModuleNotFoundError: No java install detected. Please install java to use language-tool-python.
When I run the code I get no java install detected
How to solve this issue?
I think this is not an issue with the Code itself when I run the code you provided
import language_tool_python
tl = language_tool_python.LanguageTool('en-US')
txt = "good mooorning sirr and medam my namee anderen i am from amerecia !"
m = tl.check(txt)
len(m)
I get as result a number in this case
OUT: 8
In the Documentation of the language-tool-python is written:
By default, language_tool_python will download a LanguageTool server .jar and run that in the background to detect grammar errors locally. However, LanguageTool also offers a Public HTTP Proofreading API that is supported as well. Follow the link for rate-limiting details. (Running locally won't have the same restrictions.)
So You will need Java (JRE and SKD). Also it's Written in the Requirements of the library:
Prerequisites
Python 3.5+
LanguageTool (Java 8.0 or higher)
The installation process should take care of downloading LanguageTool (it may take a few minutes). Otherwise, you can manually download LanguageTool-stable.zip and unzip it into where the language_tool_python package resides.
Source:
https://pypi.org/project/language-tool-python/
Python 2.7 - JavaError when using grammar-check 1.3.1 library
I Hope I could help.

Error in python cryptography module: _RSAPrivateKey' object has no attribute 'sign

In my Python code, I'm using cryptography module. I have a private key on disk. So, from documentation, I used this example to load that key. Then use that key to sign a message. But running the program throws AttributeError: '_RSAPrivateKey' object has no attribute 'sign'
I looked in to source code of serialization module and check return type of load_pem_private_key(). The code requires some understanding of Abstract Base Classes.
Seeking help here to debug this issue.
Here's my code
1 from cryptography.hazmat.backends import default_backend
2 from cryptography.hazmat.primitives import hashes
3 from cryptography.hazmat.primitives import serialization
4 from cryptography.hazmat.primitives.asymmetric import padding
5 from cryptography.hazmat.primitives.asymmetric import utils
6
7 from base64 import b64encode
8
9 def test_new_crypto():
10 privkey = '/path/to/privkey'
11 with open(privkey, "rb") as kf:
12 private_key = serialization.load_pem_private_key(
13 kf.read(),
14 password=None,
15 backend=default_backend()
16 )
17
18 message = b"A message I want to sign"
19 signature = private_key.sign( #### Error is here
20 message,
21 padding.PSS(
22 mgf=padding.MGF1(hashes.SHA256()),
23 salt_length=padding.PSS.MAX_LENGTH
24 ),
25 hashes.SHA256()
26 )
27
28 return b64encode(signature)
29
30 if __name__ == "__main__":
31 print(test_new_crypto())
You mention you are running an outdated version.
Upgrading from version 1.7.1 to 2.6.1 resolves the issue.
If you are here in 2022 and you use PyJWT, in cryptography version 37 the signer methods were deprecated, so you have to downgrade to version 36.0.2 of cryptography.

How to call data/variable from a python module?

I created a python module in which I stored a variable. when I run: help(connections_and_variables.connections_and_variables)
I can see in the "DATA" section the variable (dw_path).
How can I call this in the script that reads the module?
NAME
connections_and_variables.connections_and_variables - Created on Fri Jun 15 10:19:46 2018
FILE
c:\users\USER\documents\data-warehouse\connections_and_variables\connections_and_variables.py
DESCRIPTION
#author: USER
FUNCTIONS
db(name)
db_engine(name)
DATA
dw_path = r'C:\Users\USER\Documents\data-warehouse'
Just like you would access anything else from a module:
import connections_and_variables.connections_and_variables
print(connections_and_variables.connections_and_variables.dw_path)
Or:
from connections_and_variables import connections_and_variables
print(connections_and_variables.dw_path)
Or:
from connections_and_variables.connections_and_variables import dw_path
print(dw_path)

Sending files between computers remotely [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
How can I send and receive files remotely, and also push updates via python? We have a bunch of devices out in the market and they are all Windows ten based. How could we go about sending files to those machines and receive files from those machines? We would like to use python for this task. Any tutorials or articles could be awesome.
I wrote this script a while ago to send files to my remote SFTP server from my local laptop. The machines has each other's public keys:
import pysftp
import paramiko
fpaths = ['list/of', 'file/paths']
with pysftp.Connection(server, username='loginID') as sftp:
with sftp.cd('target/directory'):
for fpath in fpaths:
print("Sending:", fpath)
if not os.path.isdir(fpath):
sftp.put(fpath)
print("Permissioning", fpath)
sftp.chmod(os.path.basename(fpath), 755)
else:
dirname = os.path.basename(fpath)
if not sftp.isdir(dirname):
sftp.mkdir(dirname)
print("Permissioning", dirname)
sftp.chmod(os.path.basename(dirname), 755)
sftp.put_r(fpath, dirname)
sftp.walktree(dirname,
dcallback=lambda dname:print("Permissioning", dname) or sftp.chmod(dname, 755),
fcallback=lambda fname:print("Permissioning", fname) or sftp.chmod(fname, 755),
ucallback=lambda x:x)
Try using ftplib package for python ftp connection. Here is the small tutorial for that.
import ftplib
ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
Executing above code example:
$ python ftplib-example-1.py
- total 34
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 ..
- drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS
- lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg
- drwxr-xr-x 3 root wheel 512 May 19 1998 bin
- drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev
- drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup
- drwxr-xr-x 3 root wheel 512 May 19 1998 etc
...
Else, you may go with the SSH using Paramiko. Use whichever suits you better.
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', username='none',
password='lol')
Ftplib code reference: The ftplib module
Paramiko code reference: SSH PROGRAMMING WITH PARAMIKO | COMPLETELY DIFFERENT

Categories