Having trouble using python2.7 to access Active Directoy - python

I tried using Auth0 from Windows, but its only a trial. The GUI application is suppose to have access to the local Active Directory Users and Computers. By use
Which I am trying to figure out the simplest way to implement.

https://docs.python.org/2/library/os.path.html
import os
path = "your path"
# Check current working directory.
retval = os.getcwd()
print "Current working directory %s" % retval
# Now change the directory
os.chdir( path )
# Check current working directory.
retval = os.getcwd()
print "Directory changed successfully %s" % retval

Related

python Error: import module not found after making executable

Error image
from pathlib import Path
import linecache
import pyperclip
print('Looking for a path...')
print('Found path!')
Path('C:/Users/Akush/Documents/Warcraft III/CustomMapData/YouTD/')
a = linecache.getline('savecode.txt',7)
pyperclip.copy(a)
print('{} copied to clipboard!'.format(a))
So everything works fine in pycharm, but when i made .exe from .py it gives "Module not found" error in CMD
Do you know what i did wrong here?
thanks for help!
Since you are using pycharm, make sure you are using the correct python interpreter in the project settings. If you are using the system interpreter, the modules won't be found in a virtual environment
I cleaned up your code a little:
import os
from pathlib import Path
import linecache
import pyperclip
# Specify the path
dir = Path('C:/Users/Akush/Documents/Warcraft III/CustomMapData/YouTD/')
# Specify the file
file = 'savecode.txt'
# Start Searching for Path
print('Looking for a path...')
# Check if Path exists
if dir.is_dir():
# Set the currect working directory to the found path
os.chdir(dir)
# Let the user know the path has been found
print('Found path!')
# Check to see if the file exists
if Path(file).is_file():
# Get lines from file
a = linecache.getline(file, 7)
if a == '':
print('Nothing found in file')
else:
# Copy line to clipboard
pyperclip.copy(a)
print(f'{a} copied to clipboard!')
else:
print("File not found")
else:
print('This directory does not exist')

Is there a simpler function or one liner to check if folder exists if not create it and paste a specific file into it?

I am aiming to create a function that does the following:
Declare a path with a file, not just a folder. e.g. 'C:/Users/Lampard/Desktop/Folder1/File.py'
Create a folder in same folder as the declared file path - Calling it 'Archive'
Cut the file and paste it into the new folder just created.
If the folder 'Archive' already exists - then simply cut and paste the file into there
I have spent approx. 15-20min going through these:
https://www.programiz.com/python-programming/directory
Join all except last x in list
https://docs.python.org/3/library/pathlib.html#operators
And here is what I got to:
import os
from pathlib import Path, PurePath
from shutil import copy
#This path will change every time - just trying to get function right first
path = 'C:/Users/Lampard/Desktop/Folder1/File.py'
#Used to allow suffix function
p = PurePath(path)
#Check if directory is a file not a folder
if not p.suffix:
print("Not an extension")
#If it is a file
else:
#Create new folder before last file
#Change working directory
split = path.split('/')
new_directory = '/'.join(split[:-1])
apply_new_directory = os.chdir(new_directory)
#If folder does not exist create it
try:
os.mkdir('Archive')#Create new folder
#If not, continue process to copy file and paste it into Archive
except FileExistsError:
copy(path, new_directory + '/Archive/' + split[-1])
Is this code okay? - does anyone know a simpler method?
Locate folder/file in path
print [name for name in os.listdir(".") if os.path.isdir(name)]
Create path
import os
# define the name of the directory to be created
path = "/tmp/year"
try:
os.mkdir(path)
except OSError:
print ("Creation of the directory %s failed" % path)
else:
print ("Successfully created the directory %s " % path)
To move and cut files you can use this library
As you're already using pathlib, there's no need to use shutil:
from pathlib import Path
path = 'C:/Users/Lampard/Desktop/Folder1/File.py' # or whatever
p = Path(path)
target = Path(p.with_name('Archive')) # replace the filename with 'Archive'
target.mkdir() # create target directory
p.rename(target.joinpath(p.name)) # move the file to the target directory
Feel free to add appriopriate try…except statements to handle any errors.
Update: you might find this version more readable:
target = p.parent / 'Archive'
target.mkdir()
p.rename(target / p.name)
This is an example of overloading / operator.

os.path.exists is not working as expected in python

I am trying to create a directory in the home path and re-check if the directory exists in the home path before re-creating using os.path.exists(), but its not working as expected.
if os.access("./", os.W_OK) is not True:
print("Folder not writable")
dir_name_tmp = subprocess.Popen('pwd', stdout=subprocess.PIPE, shell=True)
dir_name_tmp = dir_name_tmp.stdout.read()
dir_name = dir_name_tmp.split('/')[-1]
dir_name = dir_name.rstrip()
os.system('ls ~/')
print "%s"%dir_name
if not os.path.exists("~/%s"%(dir_name)):
print "Going to create a new folder %s in home path\n"%(dir_name)
os.system('mkdir ~/%s'%(dir_name))
else:
print "Folder %s Already Exists\n"%(dir_name)
os.system('rm -rf ~/%s & mkdir ~/%s'%(dir_name, dir_name))
else :
print("Folder writable")
Output for the first time:
Folder not writable
Desktop Downloads Perforce bkp doc project
hello.list
Going to create a new folder hello.list in home path
Output for the 2nd time:
Folder not writable
Desktop Downloads Perforce bkp doc hello.list project
hello.list
Going to create a new folder hello.list in home path
mkdir: cannot create directory `/home/desperado/hello.list': File exists
Its not going into the else loop though the directory is existing. Am I missing something ? Share in you inputs !
Updated Working Code With Suggestions Provided: Using $HOME directory and os.path.expandusr
if os.access("./", os.W_OK) is not True:
log.debug("Folder Is Not writable")
dir_name_tmp = subprocess.Popen('pwd', stdout=subprocess.PIPE, shell=True)
dir_name_tmp = dir_name_tmp.stdout.read()
dir_name = dir_name_tmp.split('/')[-1]
dir_name = dir_name.rstrip()
log.debug("dir_name is %s"%dir_name)
dir_name_path = (os.path.expanduser('~/%s'%(dir_name))).rstrip()
log.debug("dir_name_path is %s"%(dir_name_path))
# if not os.path.exists('~/%s'%(dir_name)):
if not os.path.exists('%s'%(dir_name_path)):
log.debug("Going to create a new folder %s in home path\n"%(dir_name))
os.system('mkdir $HOME/%s'%(dir_name))
else:
log.debug("Folder %s Already Exists\n"%(dir_name))
os.system('rm -rf %s'%(dir_name_path))
os.system('mkdir $HOME/%s'%(dir_name))
else :
log.debug("Folder Is Writable")
The tilde symbol ~ representing the home directory is a shell convention. It is expanded by the shell in os.system, but it is understood literally in Python.
So you create <HOME>/<DIR>, but test for ~/<DIR>.
As mentioned by VPfB, the tilde symbol is understood literally by Python. To fix this, you need to get your actual home directory.
Now, on different platforms, there are different paths for the home directory.
To get the home directory, os.path.expanduser will be useful.
>>> import os
>>> os.path.expanduser("~")
'/Users/ashish'

Xcode Pre-actions run python script environment variables not setting ${PROJECT_DIR} properly

I am attempting to run a python script from Xcode in the Build Pre-actions:
#! /usr/bin/env python
import shutil
import os
app_name = 'name'
def skinfunction(root_src_dir, root_dst_dir):
for src_dir, dirs, files in os.walk(root_src_dir):
print(str(files))
dst_dir = src_dir.replace(root_src_dir, root_dst_dir)
if not os.path.exists(dst_dir):
os.mkdir(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
shutil.copy(src_file, dst_dir)
root_src_dir = '${PROJECT_DIR}/skins/'+str(app_name)+'/authorize_bg.imageset'
root_dst_dir = '${PROJECT_DIR}/iDetail/Images.xcassets/authorize_bg.imageset'
skinfunction(root_src_dir,root_dst_dir);
Nearing the end of the script I am trying to get the PROJECT_DIR Xcode environment variable, but it is just not working properly. Either the value is invalid or my formatting is off.
If I hard code the PROJECT_DIR value (the full url to where the project resides) and the script runs successfully.
Am I missing something in trying to get the environment variable.
Ok, I figured it out, instead of trying to get the environment variable directly by using ${PROJECT_DIR} you need to call os.getenv() function. I was able to get the environment variable by calling:
proj_dir = os.getenv('PROJECT_DIR')

Accessing Dynamically-Named Directory in Python

I'm currently putting together a script in Python which will do the following:-
Create a directory in my Dropbox folder called 'Spartacus'
Create a subdirectory in this location with the naming convention of the date and time of creation
Within this directory, create a file called iprecord.txt and information will then be written to this file.
Here is my code thusfar using Python v2.7 on Windows 7:-
import os
import time
import platform
import urllib
current_dir = os.getcwd()
targetname = "Spartacus"
target_dir = os.path.join(current_dir, targetname)
timenow = time.strftime("\%d-%b-%Y %H-%M-%S")
def directoryVerification():
os.chdir(current_dir)
try:
os.mkdir('Spartacus')
except OSError:
pass
try:
os.system('attrib +h Spartacus')
except OSError:
pass
def gatherEvidence():
os.chdir(target_dir)
try:
evidential_dir = os.mkdir(target_dir + timenow)
os.chdir(evidential_dir)
except OSError:
pass
f = iprecord.txt
with f as open:
ip_addr = urllib.urlopen('http://www.biranchi.com/ip.php').read()
f.write("IP Address:\t %s\t %s" % ip_addr, time.strftime("\%d-%b-%Y %H-%M-%S"))
x = directoryVerification()
y = gatherEvidence()
I keep on getting an error in line 26 whereby it cannot resolve the full path to the dynamically named directory (date and time) one. I've printed out the value of 'evidential_dir' and it shows as being Null.
Any pointers as to where I am going wrong? Thanks
PS: Any other advice on my code to improve it would be appreciated
PPS: Any advice on how to locate the default directory for 'Dropbox'? Is there a way of scanning a file system for a directory called 'Dropbox' and capturing the path?
os.mkdir() does not return a pathname as you might be thinking. It seems like you do inconsistent methods of the same thing at different spots of your code.
Try this:
evidential_dir = os.path.join(target_dir, timenow)
os.mkdir(evidential_dir)
And fix your other line:
f = "iprecord.txt"
os.mkdir doesn't return anything.
evidential_dir = target_dir + timenow
try:
os.mkdir(evidential_dir)
except OSError:
pass
os.chdir(evidential_dir)

Categories