Python: How to store output in a shared folder path? - python

I am creating some QR images and wish to store in a shared folder path which requires username and password to access.
qrFolder = '\\cmbpnh01-srv-03\Tidata\12. IT Projects\QR Code Creation\QA QR Code Creation'
user = 'xxx\xxx'
password = 'xxx'
winCMD = 'NET USE ' + qrFolder + ' /User:' + user + ' ' + password
qrFilename = winCMD + " " + agentcode + "_" + outlet
img.save(qrFilename + imageExt)
Error: OSError: [Errno 22] Invalid argument: 'NET USE \cmbpnh01-srv-03\Tidata\n. IT Projects\QR Code Creation\QA QR Code Creation /User:xxx\xxx xxx ALVALLSR01_ALV0030138.png'
The objective is to store all QR codes inside the shared folder path which requires credentials. You could suggest any other approaches which can achieve this objective. Thanks!

Related

Is there any way i can add sno to a file using openfile?

I want to add a serial no every time a new user information gets appended in.
def get_info():
op = open('sign in info win.txt', 'a')
serialno here is written to show where i want to add sno.
this piece of code is non working
op.write('information-no - ' + serialno + ' Name = ' + enter_name.get() + ' Password = ' + enter_password.get() + '\n')
op.close()
message = messagebox
message.showwarning(title='Saved !', message='Information Saved.')
The code in your question should already do the job, so if you're looking for a way to create a serial number perhaps you could use random.
import random
def generate_serial(length=10):
characters = list(range(0, 9))
serial = ''
for c in range(length):
serial += str( random.choice(characters) )
return serial
# Your existing code
def get_info():
serialno = generate_serial() # generate a new serialno each time
op = open('sign in info win.txt', 'a')
op.write('information-no - ' + serialno + ' Name = ' + enter_name.get() + ' Password = ' + enter_password.get() + '\n')
op.close()
message = messagebox
message.showwarning(title='Saved !', message='Information Saved.')
Here's a sample of what sort of serial numbers this would produce:
'5570344311'
'3852070084'
'5115012613'
'1655833704'
'6875243550'
Please note that while unlikely, it's entirely possible that generate_serial() will produce the same serial number for more than one user. Longer serial numbers or ones that can also contain letters reduce this probability, but if you want unique serials for every user this is not the way to go!

Python: Removing duplicate strings and staying within certain parameters

Currently, I am designing a credential database meant to hold a servername, username, and password in a text file. However, for the servername and passwords I am trying to make them unique (no two credentials / logins can have the same servername AND password, usernames can be duplicated).
For example,
# This is NOT acceptable because the servername is duplicated.
servername : username : password
google : john : 123
google : john : 321
# This is acceptable because the servername and password are unique.
servername : username : password
google : john : 123
yahoo : john : 321
I have searched stackoverflow for some answers but I was not able to find exactly what I am looking for. In my program's current state, when credentials are entered, they are simply listed right underneath the existing one and continue to add each additional credential without checking for duplicates.
# Creates the file "passdatabase.txt" for use with this code.
with open('passdatabase.txt', 'a+') as searchfile:
searchfile.close()
# Here I initialize the variable / count for the while loop
x = 1
print("\n======================="+
"\nYou chose to add a credential."
"\n-----------------------")
# User enters in a server name to be saved.
addservername = input("Server Name: ")
# User enters in a username to be saved.
addusername = input("Username: ")
# User enters in a password to be saved.
addpassword = input("Password: ")
# All inputs are combined to create a single variable in the format (servername : username : password)
addCredential = addservername + " : " + addusername + " : " + addpassword
# Loops until the user enters a valid submission (either [y] or [n]) to confirm information.
while x == 1:
# Input information is displayed for user to confirm.
confirmCredential = input("~~~~~~~~~~~~~~~~~~~~~~~" +
"\nPlease verify the entered credentials.\n" +
"\nServer Name: [" +
addservername + "]" +
"\nUsername: [" +
addusername + "]" +
"\nPassword: [" +
addpassword + "]" +
"\n\nIs the information correct? (y/n): ")
print("~~~~~~~~~~~~~~~~~~~~~~~")
if confirmCredential == "y":
x = 2
with open('passdatabase.txt', 'r') as searchfile:
lines_seen = set(open('passdatabase.txt'))
for addCredential in (searchfile, 1):
if addCredential not in lines_seen:
with open('passdatabase.txt', 'a+') as searchfile:
# I set the format of the credential to save in the text file as
# servername : username : password.
searchfile.write("\n" + addservername + " : " + addusername + " : " + addpassword)
print("[!] SUCCESS! Your credentials have successfully been stored [!]" +
"\n=======================")
# This breaks the for loop so it does not continue the code.
break
else:
print('Duplicate credential detected!')
elif confirmCredential == "n":
x = 2
print("[!] Your credentials have not been stored [!]" +
"\n=======================")
else:
print("###########################################################" +
"\n[!!!ERROR!!!] PLEASE ENTER EITHER [y] OR [n]. [!!!ERROR!!!]\n" +
"###########################################################")
My questions / requests in one simple list are as follows:
- How do I ensure that the user can only enter in unique entries for their servername and password credentials while allowing duplicate username entries?
- If a duplicate is detected, I would like the code to stop from going further and ask the user for input again until a proper unique credential is provided.
- Should I be using a set or an array? (Data-order does not matter)
- I've seen quite a few duplicate checking scripts that involve the use of 2 .txt files, is this possible with only 1?
- In the future I plan on adding encryption to the password entries, password strength checker, and possibly a credential log (of who has logged in).
- Any input is welcome as I am always willing to learn!
I am fairly new to Python coding and I would really just like some guidance on what I should be looking into next, I'm honestly not sure if I am even headed in the right direction.
Thanks
Maybe you should use sqlite instead of pure text file.
If you really want to implement database feature in a txt file:
Use set for tuple(servername, password), check if exist before appending to file. Remember to load all exist ones from your txt file before ask user to input.
You'd better use a file lock to make sure that only one instance of your script run at the same time.

Arcmap script will not print messages in arcmap console

I have a Python script for Arcmap that I wrote. I'm trying to create a tool that reprojects all the feature classes within the workspace to a specified feature class.
The problem that I'm having is that I cannot get Arcmap to print the "completed" messages. The messages that I want to have appear will print when I hard-code the variables and run it as a script, but they will not print in Arcmap. You can see in the code below that I have specific printed messages that I want printed, but they just won't appear.
Code:
#Import modules
import arcpy, os
#Set workspace directory
from arcpy import env
#Define workspace
inWorkspace = arcpy.GetParameterAsText(0)
env.workspace = inWorkspace
env.overwriteOutput = True
try:
#Define local feature class to reproject to:
targetFeature = arcpy.GetParameterAsText(1)
#Describe the input feature class
inFc = arcpy.Describe(targetFeature)
sRef = inFc.spatialReference
#Describe input feature class
fcList = arcpy.ListFeatureClasses()
#Loop to re-define the feature classes and print the messages:
for fc in fcList:
desc = arcpy.Describe(fc)
if desc.spatialReference.name != sRef.name:
print "Projection of " + str(fc) + " is " + desc.spatialReference.name + ", so re-defining projection now:\n"
newFc = arcpy.Project_management(fc, "projected_" + fc, sRef)
newFeat = arcpy.Describe(newFc)
count = arcpy.GetMessageCount()
print "The reprojection of " + str(newFeat.baseName) + " " + arcpy.GetMessage(count-1) + "\n"
#Find out which feature classes have been reprojected
outFc = arcpy.ListFeatureClasses("projected_*")
#Print a custom messagae describing which feature classes were reprojected
for fc in outFc:
desc = arcpy.Describe(fc)
name = desc.name
name = name[:name.find(".")]
name = name.split("_")
name = name[1] + "_" + name[0]
print "The new file that has been reprojected is named " + name + "\n"
except arcpy.ExecuteError:
pass
severity = arcpy.GetMaxSeverity()
if severity == 2:
print "Error occurred:\n{0}".format(arcpy.GetMessage(2))
elif severity == 1:
print "Warning raised:\n{1}".format(arcpy.GetMessage(1))
else:
print "Script complete"
When I upload a script into an Arcmap toolbox, the following lines (From the above code) will NOT print:
print "Projection of " + str(fc) + " is " + desc.spatialReference.name + ", so re-defining projection now:\n"
print "The reprojection of " + str(newFeat.baseName) + " " + arcpy.GetMessage(count-1) + "\n"
print "The new file that has been reprojected is named " + name + "\n"
How can I fix this?
print only prints the messages while your script is running in Python interpreter. In order to print logs while the script is running in ArcGIS Toolbox, you need to use arcpy.AddMessage()
arcpy.AddMessage("Projection of {0} is {1}, so re-defining projection now: ".format(str(fc), desc.spatialReference.name)

Django logging with dynamic name

I'm trying to create logs in my django project, but i want a log with a different filename for each execution. What i did so far is set it up like it's written here, but this creates one log and puts everything in it. I want a log per execution with a dynamic name, like instance name + date or something. Can this be done?
Edit: Code example of creating a scheduled task. (I think you will get what it does from this)
def create_schedule (inst):
path_task=os.path.join(os.path.join(os.path.dirname(__file__),os.pardir),os.pardir)
path_task=path_task[:len(path_task)-2]+'executeInstance.py'
tr='"py '+path_task + ' ' + str(inst.id)+'"'
tn='Inst ' + str(inst.id)
time=inst.schedule.time
if inst.schedule.scheduleType=='Weekly':
w_days=''
for day in inst.schedule.weekDays.all():
if w_days!='':
w_days=w_days+','
w_days=w_days+day.weekDay[:3].upper()
tn='"'+tn+'"'
cmd_sch='schtasks /create /tn ' + tn + ' /tr ' + tr + ' /sc weekly /d '+ w_days + ' /st ' + time + ' /RU SYSTEM'
result = subprocess.check_output(cmd_sch, shell=True)
And then catching an exception in executeInstance.py
except smtplib.SMTPDataError as e:
status_log='Error'
error_desc='Message size too big for your email server'
inst=Instance.objects.get(id=instance_id)
log=Log(instance=inst,status=status_log,errorDesc=error_desc,executionDate=datetime.now())
log.save()
logger.error(log)
Maybe try to play with time rotated log files? https://docs.python.org/2.7/library/logging.handlers.html#rotatingfilehandler

Python code to send command through command line

final="cacls " + "E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str
os.system(final)
I am trying to set permission to a folder Using Python but while running this command , User input needs to be provided too i.e
it asks ARE YOU SURE(Y/N) and the user needs to enter "Y" or "N"
Is there any way to use python to send the user input "Y" along with the above code?
pro = subprocess.Popen(final,shell=True, stdin=subprocess.PIPE)
pro.communicate(bytes("Y\r\n",'utf-8'))
I have added the following code . The program exits without setting the permission.
http://jimmyg.org/blog/2009/working-with-python-subprocess.html#writing-to-standard-input
Try using the subprocess module
import subprocess
cmd = ["cacls", "E:/" + list1[2], list1[3], "/p", str]
pro = subprocess.Popen(final, stdin=subprocess.PIPE)
pro.communicate("y\r\n")
As a smart programmer, use PBS
Then, the code is:
from pbs import type as echo# Isn't it echo for Windows? If not, use the correct one
script = Command("/path/to/cacls ")
print script(echo("Y"), ("E:/" + "\"" + list1[2] + " " + list1[3] + "\"" + " /p " + str).split())

Categories

Resources