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)
Related
I am trying to read banner from one of the switch using paramiko module in python. This is the code which i am using for the same
import socket
import sys
import paramiko
import subprocess
a=paramiko.SSHClient()
a.set_missing_host_key_policy(paramiko.AutoAddPolicy())
a.connect('10.22.158.19',username='admin',password='airwave')
b=a.invoke_shell()
b.recv_ready()
b.recv(1000)
When I run above I am not getting any output , but when i comment last line in the script and when i execute last command in shell b.recv(1000) is giving actual output
>>>
>>> b.recv(1000)
'Last login: Tue Aug 22 23:10:25 2017 from 10.20.14.150\r\r\n(AirwaveMM-19) [mynode] #'
>>>
Does anyone of you have any clue what is wrong here ?
You should write like this:
while not b.recv_ready():
time.sleep(0.1)
print b.recv(1000)
The recv_ready() function checks if data is ready but it does not wait for the data to be ready.
File setup:
...\Project_Folder
...\Project_Folder\Project.py
...\Project_folder\Script\TestScript.py
I'm attempting to have Project.py import modules from the folder Script based on user input.
Python Version: 3.4.2
Ideally, the script would look something like
q = str(input("Input: "))
from Script import q
However, python does not recognize q as a variable when using import.
I've tried using importlib, however I cannot figure out how to import from the Script folder mentioned above.
import importlib
q = str(input("Input: "))
module = importlib.import_module(q, package=None)
I'm not certain where I would implement the file path.
Repeat of my answer originally posted at How to import a module given the full path?
as this is a Python 3.4 specific question:
This area of Python 3.4 seems to be extremely tortuous to understand, mainly because the documentation doesn't give good examples! This was my attempt using non-deprecated modules. It will import a module given the path to the .py file. I'm using it to load "plugins" at runtime.
def import_module_from_file(full_path_to_module):
"""
Import a module given the full path/filename of the .py file
Python 3.4
"""
module = None
try:
# Get module name and path from full path
module_dir, module_file = os.path.split(full_path_to_module)
module_name, module_ext = os.path.splitext(module_file)
# Get module "spec" from filename
spec = importlib.util.spec_from_file_location(module_name,full_path_to_module)
module = spec.loader.load_module()
except Exception as ec:
# Simple error printing
# Insert "sophisticated" stuff here
print(ec)
finally:
return module
# load module dynamically
path = "<enter your path here>"
module = import_module_from_file(path)
# Now use the module
# e.g. module.myFunction()
I did this by defining the entire import line as a string, formatting the string with q and then using the exec command:
imp = 'from Script import %s' %q
exec imp
Below is the code i am which i tried, I am new to python, could someone let me know what shall i do
#opening a 'Newfile' to write in
file_list=open('file_list.txt','w')
#taking the list of file which i have to write in file
list_files = os.system("ls -1 /amxusers7/inf/aimsys/netabp6/ALL_SCRIPTS/VOICE")
#trying to write in a Newfile
file_list.writelines(list_files)
I am getting error:
Traceback (most recent call last):
File "testPuneet.py", line 30, in ?
file_list.writelines(list_files)
TypeError: writelines() requires an iterable argument
If you are using Python, you might as well do it the Python way:
import os
with open('file_list.txt','w') as file_list:
list_files = os.listdir('/amxusers7/inf/aimsys/netabp6/ALL_SCRIPTS/VOICE')
file_list.write('\n'.join(list_files))
On Unix, os.system returns the exit code of the process you invoked. So, os.system("ls") will give you an integer, not a list of files.
Instead, use the subprocess module. The check_output method will give you the values that are printed to the screen.
import subprocess
result_of_ls = subprocess.check_output(["ls", "-l", "/amxusers7/inf/aimsys/netabp6/ALL_SCRIPTS/VOICE"])
As an example gives:
total 75032\n-rw-rw-r-- 1 user user 0 Jun 3 22:04 122.txt\n-rw-rw-r-- 1 user user 0 Jun 3 22:04 154.txt\n-r-------- 1 user user 8666 Mar 29 22:11 2731_74814450810_2074865_n.jpg\n-rw-rw-r-- 1 user user 111872 May 30 21:40 3065397482_cd8b581c9a.jpg\n-rw-rw-r-- 1 user user 24661 Jun 18 13:11 375585_782393371042_1430263587_n.jpg\n
Taking the single string returned by check_output and turning it into a list of filenames is left as an exercise to the reader.
...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
I am new to python and I'm trying to create a program that creates a directory with todays date, create a sandbox into that directory and run the make file in the sandbox. I am having trouble getting the variables to be picked up in the os.path lines. The code is posted below:
#!/usr/bin/python
import mks_function
from mks_function import mks_create_sandbox
import sys, os, time, datetime
import os.path
today = datetime.date.today() # get today's date as a datetime type
todaystr = today.isoformat() # get string representation: YYYY-MM-DD
# from a datetime type.
if not os.path.exists('/home/build/test/sandboxes/'+todaystr):
os.mkdir(todaystr)
else:
pass
if not os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/project.pj'):
mks_create_sandbox()
else:
pass
if os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/Makefile'):
os.system("make >make_results.txt 2>&1")
Any help would be appreciated,
Thanks
a couple of notes:
#!/usr/bin/env python
# import mks_function .. you won't need this ...
from mks_function import mks_create_sandbox
import os, datetime
# import time, sys .. these aren't used in this snippet
# import os.path .. just refer to os.path, since os is already imported
# get today's date as a datetime type
todaystr = datetime.date.today().isoformat()
# .. use os.path.join()
if not os.path.exists(os.path.join('/home/build/test/sandboxes/', todaystr)):
os.mkdir(os.path.join('/home/build/test/sandboxes/', todaystr))
# .. 'else: pass' is unnecessary
if not os.path.exists(os.path.join(
'/home/build/test/sandboxes/', todaystr, '/new_sandbox/project.pj')):
# i'm not seen, that the sandbox is created in the right directory here
# maybe you should change the working directory via ..
# os.chdir(os.path.join('/home/build/test/sandboxes/', todaystr))
mks_create_sandbox()
if os.path.exists(os.path.join(
'/home/build/test/sandboxes/', todaystr, '/new_sandbox/Makefile')):
# .. change to the right directory
os.chdir(os.path.join(
'/home/build/test/sandboxes/', todaystr, '/new_sandbox/'))
os.system("make > make_results.txt 2>&1")
Please try adding chdir code before you call make
if os.path.exists('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/Makefile'):
os.chdir('/home/build/test/sandboxes/'+todaystr+'/new_sandbox/')
os.system("make >make_results.txt 2>&1")
I think you want to change a few things:
def makeSandbox():
sbdir = os.path.join('/home/build/test/sandboxes/',todaystr)
if not os.path.exists(sbdir):
os.mkdir(sbdir) # <- fully qualified path
else:
pass
And I don't really see what variables need to be picked up, seems fine to me.
Not sure what the module mks_function does. But I see one issue with your code.
For example,
if not os.path.exists('/home/build/test/sandboxes/'+todaystr):
os.mkdir(todaystr)
In the above chunk you check if the directory "/home/build/test/sandboxes/+'todaystr'"
exists and a create a directory by name "value contained in todaystr" (say 2009-12-21). This creates directory by name '2009-12-21' in the current working directory, rather than under : /home/build/test/sandboxes
which is what you intended I guess. So change to the above directory before the call to mkdir. Also it is good to check the return status of mkdir to verify if the directory creation succeeded.
path module might help in this case:
#!/usr/bin/env python
from mks_function import mks_create_sandbox
import os, datetime
from path import path
sandboxes = path('/home/build/test/sandboxes/')
today = sandboxes / datetime.date.today().isoformat()
today.mkdir() # create directory if it doesn't exist
project = today / "new_sandbox/project.pj"
project.parent.mkdir() # create sandbox directory if it doesn't exist
if not project.isfile():
mks_create_sandbox()
makefile = project.parent / "Makefile"
if makefile.isfile():
os.chdir(makefile.parent)
os.system("make >make_results.txt 2>&1")