How to use relFilePath method in fMBT

Best Python code snippet using fMBT_python

spc_functions.py

Source:spc_functions.py Github

copy

Full Screen

1import os2import csv3import getpass4import json5from pathlib import Path6import pickle7import re8import requests9from tempfile import NamedTemporaryFile10import shutil11# Functions available in the file :12# check_password13# check_return_password14# current_user15# change_current_user16# get_token17# change_token18# file_name19# mdsum20# get_scheme21# change_scheme22# get_decryption_key23# file_type24# create_login_csv25# login26# login_user27# save28# req_send29# logout30# upload_file31# upload_file_info32# upload_file_content33# display_filelist34# delete_file35# change_encryption_scheme36# download_file37# sync_file_from_client38# sync_file_from_server39# sync_dir_from_client40# sync_delete_from_server41# sync_dir_from_server42# sync_delete_from_client43def check_password(user):44 with open(os.getenv('HOME')+'/loginData.csv','r') as csvfile:45 reader=csv.DictReader(csvfile)46 for row in reader:47 if(row['username'] == user):48 return row['password']49 return ''50def check_return_password(user):51 with open(os.getenv('HOME')+'/loginData.csv','r') as csvfile :52 reader=csv.DictReader(csvfile)53 for row in reader :54 if (row['username'] == user):55 if (row['savepassword'] == 'yes'):56 return row['password']57 else:58 print('No password saved.')59 return ''60 return ''61def check_user(user):62 with open (os.getenv('HOME')+'/loginData.csv','r') as csvfile:63 reader=csv.DictReader(csvfile)64 for row in reader :65 if (row['username'] == user):66 return True67 return False68def current_user():69 with open(os.getenv('HOME')+'/current_user.txt','r') as f:70 return f.read()71def change_current_user(user):72 with open(os.getenv('HOME')+'/current_user.txt','w') as f:73 f.write(user)74def get_token():75 with open(os.getenv('HOME')+'/token.txt','r') as f:76 return f.read()77def change_token(token):78 with open(os.getenv('HOME')+'/token.txt','w') as f:79 f.write(token) 80def file_name(filepath):81 return os.popen('basename '+ filepath).read().split('\n')[0]82def mdsum(filepath):83 relfilepath=os.path.relpath(filepath,os.getenv('HOME'))84 homefilepath=os.getenv('HOME')+'/'+relfilepath85 command='md5sum '+homefilepath86 return os.popen(command).read().split()[0]87 88def get_scheme(user):89 with open(os.getenv('HOME')+'/loginData.csv','r') as csvfile:90 reader=csv.DictReader(csvfile)91 for row in reader:92 if(row['username'] == user):93 return row['scheme']94 return ''95def change_scheme(user,scheme):96 with open(os.getenv('HOME')+'/loginData.csv','w') as csvfile:97 writer=csv.DictWriter(csvfile)98 for row in writer:99 if(row['username'] == user):100 row['scheme']=scheme101def get_decryption_key(user):102 with open(os.getenv('HOME')+'/loginData.csv','r') as csvfile:103 reader=csv.DictReader(csvfile)104 for row in reader:105 if (row['username'] == user):106 return row['decryptionkey']107def change_decryption_key(user):108 key=''109 while (key == ''):110 key=input('Enter encryption key: ')111 with open(os.getenv('HOME')+'/loginData.csv','w') as csvfile:112 writer=csv.DictWriter(csvfile)113 for row in writer:114 if(row['username'] == user):115 row['decryptionkey']=key116 print('Encryption key changed.')117def file_type(filename):118 if(filename.lower().endswith('.pdf')):119 return 'pdf'120 elif(filename.lower().endswith(('.jpg','.png','.jpeg','.gif','.webp','.svg','.ai','.ps'))):121 return 'image'122 elif(filename.lower().endswith(('.flv','.avi','.mkv','.mov','.mp4','.mpg','.mwv','.3pg','.asf','.rm','.swf'))):123 return 'video'124 elif(filename.lower().endswith(('.aif','.cda','.mid','.midi','.mp3','.ogg','.mpa','.wav','.wma','wpl'))):125 return 'audio'126 elif(filename.lower().endswith(('.zip','tar.gz','.7z','.rar','.pkg','.arj','.deb','.rpm'))):127 return 'archieve'128 else:129 return 'document'130def change_sync_status(syncstatus):131 token=get_token()132 data={133 'syncstatus': str(syncstatus)134 }135 headers={136 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',137 'Authorization':token138 }139 url='http://10.2.224.70:8000/files/sync/'140 r=requests.post(url,data=data,headers=headers)141def get_sync_status():142 token=get_token()143 headers={144 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',145 'Authorization':token146 }147 url='http://10.2.224.70:8000/files/get-sync/'148 r=requests.get(url,headers=headers)149 json_data=json.loads(r.content)150 print(json_data)151 js=json.dumps(json_data[0]['sync_status'])152 return js153def create_login_csv():154 file_exists=os.path.isfile(os.getenv('HOME')+'/loginData.csv')155 if not file_exists:156 with open (os.getenv('HOME')+'/loginData.csv', 'w') as csvfile:157 fieldnames=['username','password','savepassword','scheme','decryptionkey']158 writer=csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=fieldnames)159 writer.writeheader()160def login(user):161 create_login_csv()162 defaultscheme='aes'163 print('Username: '+user)164 if check_user(user):165 login_user(user)166 else:167 response=input('Have you registered? [Y/N]')168 if (response == 'Y' or response == 'y'): 169 print('Encryption schemes available: ')170 print('1. AES')171 print('2. DES')172 n=int(input('To select the scheme,type the corresponding index: '))173 if (n == 1 or n == 2):174 if (n == 1):175 defaultscheme='aes'176 else:177 defaultscheme='des'178 save(user,'','no',defaultscheme,'')179 login_user(user)180 elif (response == 'N' or response == 'n'):181 print('To use this service, you need to register at :')182 print('http://10.2.224.70:8000/register/')183 184def login_user(user):185 defaultscheme='aes'186 password=check_return_password(user)187 if(password != ''):188 req_send(user,password)189 else:190 password=str(getpass.getpass(prompt='Password: ', stream=None)) 191 if (req_send(user,password) == 200):192 savepassword=input('Do you want to save your password? [Y/N]')193 if(savepassword == 'Y' or savepassword == 'y'):194 save(user,password,'yes',defaultscheme,'')195 print('Password saved successfully.')196 elif (savepassword == 'N' or savepassword == 'n'):197 save(user,'','no',defaultscheme,'')198 else:199 print('Value not recognized. [Y/N]')200 else:201 print('Provided username or password is incorrect.')202def save(user,password,command,scheme,decryptionkey):203 rows=[]204 with open(os.getenv('HOME')+'/loginData.csv','r') as csvfile:205 reader=csv.DictReader(csvfile)206 for row in reader:207 if(row['username'] != user):208 rows.append(row)209 with open(os.getenv('HOME')+'/loginData.csv','w') as csvfile:210 fieldnames=['username','password','savepassword','scheme','decryptionkey']211 writer=csv.DictWriter(csvfile,fieldnames=fieldnames)212 writer.writeheader()213 writer.writerows(rows)214 with open(os.getenv('HOME')+'/loginData.csv','a') as f_append:215 fieldnames=['username','password','savepassword','scheme','decryptionkey']216 writer=csv.DictWriter(f_append,fieldnames=fieldnames)217 writer.writerow({'username':user,'password':str(password),'savepassword':command,'scheme':scheme, 'decryptionkey':'',})218def req_send(user,password):219 headers={220 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'221 }222 login_data={223 'username': user,224 'password': password,225 'action':'login'226 }227 with requests.Session() as s:228 url='http://10.2.224.70:8000/files/api-token-auth/'229 r=s.post(url, data=login_data, headers=headers)230 if(r.status_code == 200):231 Token='JWT '+(r.json())['token']232 print('Login successful.')233 change_current_user(user)234 change_token(Token)235 else:236 print('Provided password is incorrect. Try again.')237 save(user,'','no',get_scheme(user),'')238 return r.status_code239def logout(user):240 if (current_user() != ''):241 if (current_user() == user):242 change_current_user('')243 change_token('') 244 print('Logout successful.')245 else:246 print('Provided username is incorrect.')247 else:248 print('No user is logged in.')249def upload_file(filepath):250 relfilepath=os.path.relpath(filepath,os.getenv('HOME'))251 if (os.path.getsize(os.getenv('HOME')+'/'+relfilepath) > 0):252 response=upload_file_info(filepath)253 if (response == 1):254 if upload_file_content(filepath):255 print('File successfully uploaded.')256 else:257 print('Error while encrypting the file.') 258 elif (response == 2):259 if (delete_file(filepath) == 204):260 upload_file(filepath)261 elif (response == 3):262 print('Process aborted by user.')263 elif (response == 4):264 print('Unknown error.')265 else:266 print('File empty.')267def upload_file_info(filepath):268 filename=file_name(filepath)269 filetype=file_type(filename)270 md5sum=mdsum(filepath)271 relfilepath=os.path.relpath(filepath,os.getenv('HOME'))272 token=get_token()273 fileinfo={274 'filename': relfilepath,275 'filetype': filetype,276 'md5sum': md5sum277 }278 headers={279 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',280 'Authorization':token281 }282 url2='http://10.2.224.70:8000/files/'+relfilepath+'/'283 r2=requests.get(url2,headers=headers)284 if (r2.status_code == 404):285 url1='http://10.2.224.70:8000/files/create/'286 r1=requests.post(url1,data=fileinfo,headers=headers)287 return 1288 elif (r2.status_code == 200):289 response=input('File already exists. Do you wish to overwrite it? [Y/N]')290 if (response == 'Y' or response =='y'):291 return 2292 elif (response == 'N' or response == 'n'):293 return 3294 else:295 return 4296def upload_file_content(filepath):297 user=current_user()298 scheme=get_scheme(user)299 filename=file_name(filepath)300 relfilepath=os.path.relpath(filepath,os.getenv('HOME'))301 encryptedfilepath=filepath+'.'+scheme302 token=get_token()303 if (scheme == 'aes'):304 os.system('cat '+filepath+' | openssl enc -base64 | openssl aes-256-cbc -a -salt > '+encryptedfilepath)305 elif (scheme == 'des'):306 os.system('cat '+filepath+' | openssl enc -base64 | openssl des-cbc -a -salt > '+encryptedfilepath)307 content=''308 with open(encryptedfilepath,'r') as f:309 content += f.read()310 content.replace('\n','')311 os.system('rm -f '+encryptedfilepath)312 fileinfo={313 'filename': relfilepath,314 'content': content315 }316 headers={317 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',318 'Authorization':token319 }320 url='http://10.2.224.70:8000/files/upload/'321 r=requests.post(url,data=fileinfo,headers=headers)322 if(r.status_code == 201):323 return True324 else:325 return False326 # else:327 # command ='openssl genrsa -aes128 -passout pass:'+p+' -out p.pem'328 # os.popen(command).read()329 # command='openssl rsa -in p.pem -passin pass:'+p+' -pubout -out p.pub'330 # os.popen(command).read()331 # command='openssl rsautl -encrypt -pubin -inkey public.key -in plaintext.txt -out encrypted.txt'332def display_filelist():333 token=get_token()334 headers={335 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',336 'Authorization':token337 }338 url='http://10.2.224.70:8000/files/'339 r=requests.get(url, headers=headers)340 if r.status_code != 500:341 json_lst=r.json()342 print('{} {} {}'.format('Filename','Filetype','Date'))343 for lst in json_lst:344 print('{} {} {}'.format(lst['filename'], lst['filetype'], lst['date_upload']))345 else:346 print('No files uploaded or shared.')347def delete_file(filepath):348 relfilepath=os.path.relpath(filepath,os.getenv('HOME'))349 print('File: '+relfilepath)350 token=get_token()351 headers={352 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',353 'Authorization':token354 }355 url='http://10.2.224.70:8000/files/'+relfilepath+'/delete/'356 r=requests.delete(url,headers=headers)357 if (r.status_code == 204):358 print('File deleted successfully.')359 return 204360 elif (r.status_code == 404):361 print('No such file exists.')362 return 404363 else: 364 print('Unknown error.')365 return r.status_code366def change_encryption_scheme(command):367 user=current_user()368 last_scheme=get_scheme(user)369 last_key=get_decryption_key(user)370 if (command == 'list'):371 print('Encryption schemes available: ')372 print('1. AES')373 print('2. DES')374 elif (command == 'change_scheme'):375 print('1. AES')376 print('2. DES')377 n=int(input('To change the scheme,type the corresponding number: '))378 if (n == 1 or n == 2):379 password=check_return_password(user)380 if (password == ''):381 password=str(getpass.getpass(prompt='Password: ',stream=None))382 if (password == check_password(user)):383 if (n == 1):384 change_scheme(user,'aes')385 else:386 change_scheme(user,'des')387 if (get_scheme(user) != last_scheme):388 key=change_decryption_key(user)389 else:390 key=change_decryption_key(user)391 else :392 print('Entered password is incorrect.')393 else :394 print('Please select a valid option.')395def download_file(filepath):396 user=current_user()397 relfilepath=os.path.relpath(filepath,os.getenv('HOME'))398 scheme=get_scheme(user)399 token=get_token()400 headers={401 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',402 'Authorization': token403 }404 url='http://10.2.224.70:8000/files/'+relfilepath+'/'405 r=requests.get(url,headers=headers)406 json_data=json.loads(r.content)407 json_content=json.dumps(json_data['content'])408 json_content = json_content.split('"')[1]409 json_md5sum = json.dumps(json_data['md5sum'])410 if (scheme == 'aes'):411 with open('input.aes','w') as f:412 f.write(re.sub('(.{64})','\\1\n',json_content,0,re.DOTALL))413 os.system('cat input.aes | openssl enc -base64 -d | openssl aes-256-cbc -d -a | openssl enc -base64 -d > '+os.getenv('HOME')+'/'+relfilepath)414 os.system('rm -f input.aes')415 elif (scheme == 'des'):416 with open('input.aes','w') as f:417 f.write(re.sub('(.{64})','\\1\n',json_content,0,re.DOTALL))418 os.system('cat input.aes | openssl enc -base64 -d | openssl des-cbc -d -a | openssl enc -base64 -d > '+os.getenv('HOME')+'/'+relfilepath)419 os.system('rm -f input.aes')420 # md5sum=mdsum(os.getenv('HOME')+'/'+relfilepath)421 # if (json_md5sum.split('\"')[1] == md5sum):422 # return 1423 # else:424 # return 2425 return 1426 427def sync_file_from_client(filepath):428 filename=file_name(filepath)429 md5sum=mdsum(filepath)430 relfilepath=os.path.relpath(filepath,os.getenv('HOME'))431 token=get_token()432 headers={433 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',434 'Authorization':token435 }436 url='http://10.2.224.70:8000/files/'+relfilepath+'/'437 r=requests.get(url,headers=headers)438 print('Syncing: '+filename)439 if (r.status_code == 404):440 upload_file(filepath)441 else:442 json_data=json.loads(r.content)443 json_md5sum=json.dumps(json_data['md5sum'])444 if (json_md5sum.split('\"')[1] != md5sum):445 delete_file(filepath)446 upload_file(filepath)447 print('Sync successful.')448def sync_file_from_server(filepath):449 filename=file_name(filepath)450 md5sum=mdsum(filepath)451 relfilepath=os.path.relpath(filepath,os.getenv('HOME'))452 token=get_token()453 headers={454 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',455 'Authorization':token456 }457 url='http://10.2.224.70:8000/files/'+relfilepath+'/'458 r=requests.get(url,headers=headers)459 json_data=json.loads(r.content)460 json_md5sum=json.dumps(json_data['md5sum'])461 if (r.status_code == 404):462 print('No such file exists.')463 else:464 print('Syncing: '+filename)465 json_data=json.loads(r.content)466 json_md5sum=json.dumps(json_data['md5sum'])467 if (json_md5sum.split('\"')[1] != md5sum):468 os.system('rm -rf '+os.relfilepath)469 download_file(filepath)470 print('Sync successful.')471def sync_dir_from_client(dirpath):472 for f in os.listdir(dirpath):473 fpath=dirpath+'/'+f474 if os.path.isfile(fpath):475 sync_file_from_client(fpath)476 elif os.path.isdir(fpath):477 sync_dir_from_client(fpath)478def sync_delete_from_server(dirpath):479 token=get_token()480 headers={481 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',482 'Authorization':token483 }484 url='http://10.2.224.70:8000/files/'485 r=requests.get(url,headers=headers)486 json_data=json.loads(r.content)487 for file_info in json_data:488 filepath=file_info['filename']489 reldirpath=os.path.relpath(dirpath,os.getenv('HOME'))490 relfilepath=os.path.relpath(filepath,reldirpath)491 if not relfilepath.startswith('..'):492 file_exists=os.path.isfile(os.getenv('HOME')+'/'+filepath)493 if not file_exists:494 delete_file(os.getenv('HOME')+'/'+filepath)495def sync_dir_from_server(dirpath):496 token=get_token()497 headers={498 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',499 'Authorization':token500 }501 url='http://10.2.224.70:8000/files/'502 r=requests.get(url, headers=headers)503 json_data=r.json()504 for file_info in json_data:505 filepath=os.getenv('HOME')+'/'+file_info['filename']506 reldirpath=os.path.relpath(dirpath,os.getenv('HOME'))507 relfilepath=os.path.relpath(filepa8th,dirpath)508 if not relfilepath.startswith('..'):509 if os.path.isfile(filepath):510 sync_file_from_server(filepath)511 else:512 if (relfilepath.count('/') > 0 ):513 innerdir_list=relfilepath.split('/')[0:-1]514 filename=relfilepath.split('/')[-1]515 innerdir=''516 for d in innerdir_list:517 innerdir=innerdir+'/'+d518 final_path=os.getenv('HOME')+'/'+reldirpath+innerdir519 os.system('mkdir -p '+final_path)520 os.system('touch '+final_path+'/'+filename)521 sync_file_from_server(final_path+'/'+filename)522 else:523 final_path=os.getenv('HOME')+'/'+reldirpath524 os.system('touch '+final_path+'/'+filename)525 sync_file_from_server(final_path+'/'+filename)526def sync_delete_from_client(dirpath):527 reldirpath=os.path.relpath(dirpath,os.getenv('HOME'))528 homedirpath=os.getenv('HOME')+'/'+reldirpath529 for d in os.listdir(homedirpath):530 if os.path.isfile(homedirpath+'/'+d):531 token=get_token()532 headers={533 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',534 'Authorization':token535 }536 url='http://10.2.224.70:8000/files/'+reldirpath+'/'+d+'/'537 r=requests.get(url,headers=headers)538 if (r.status_code == 404):539 os.system('rm -f '+homedirpath+'/'+d)540 elif os.path.isdir(homedirpath+'/'+d):541 sync_delete_from_client(dirpath+'/'+d)542 if not os.listdir(dirpath):...

Full Screen

Full Screen

RenderAssets.py

Source:RenderAssets.py Github

copy

Full Screen

1import subprocess, time, winreg, psutil, os, json2############################################################################3#Program that will start daz studio,4#and render assets from asset list created by ListAssets.py.5############################################################################6#set the daz studio script that runs on launch7directory = "C:/Daz 3D/Applications/Data/DAZ 3D/AssetRender" #Directory of Render output information.8dazAssets = "C:/Daz 3D/Applications/Data/DAZ 3D/AssetRender/assets.txt" #file path of daz asset file9############################################################################10#read in daz list of assets from ListAssets.py to this python script11dazAssetListLoc = "C:/Daz 3D/Applications/Data/DAZ 3D/AssetRender/assets.txt" #file location of daz asset list. OUTPUT FORMAT UNDECIDED. List is output by daz studio. ASSUME JSON.12fileIn = open(dazAssetListLoc, "r")13lines = fileIn.readlines()14fileIn.close()15############################################################################16#take above list and store in array17assetArray = []18#Take asset list txt file and add each row to new python list.19for line in lines:20 #print('x')21 if '.duf' in line:22 line = line.strip() #removing any return characters in string23 assetArray.append(line) #adding string to array24 25#store array in text file. Test only.26arrayFile = open(directory + '/' + 'arrayTest.txt', 'w')27for item in assetArray:28 arrayFile.write("%s\n" % item)29arrayFile.close()30#print("TEST ARRAY STORED AND WRITTEN TO FILE.")31 32############################################################################33#Check if progress file exists 34#the path to the progress file35progressFilePath = 'C:/Daz 3D/Applications/Data/DAZ 3D/AssetRender/renderProgressFile.txt'36currentPos = 037if os.path.isfile(progressFilePath):38 fileIn = open(progressFilePath, "rt")39 currentProgress = fileIn.readline()40 currentProgress = currentProgress.strip()41 fileIn.close()42 #if the progress file exists. Store the position of the currentProgress.43 #this is where the current process will start from if available - else start from beginning.44 for x in assetArray:45 if x == currentProgress:46 #print("Temp progress check")47 currentPos+=148 break49 else:50 currentPos+=151else:52 #create file53 newFile = open(progressFilePath, 'w+')54 newFile.close()55############################################################################56#set start up script to render daz assets from list stored above57reg = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) #open the registry58sKey = winreg.OpenKey(reg, "SOFTWARE\DAZ\Studio4", 0 , winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY) #get the element to be updated59newPath = "C:/Daz 3D/Applications/Data/DAZ 3D/My DAZ 3D Library/Scripts/Shortt/RenderAsset.dsa" #insert location of script that will RENDER list of assets here.60winreg.SetValueEx(sKey, 'StartupScene', '0' , winreg.REG_SZ, newPath) #set the new value61winreg.CloseKey(sKey) #close the value62winreg.CloseKey(reg) #close the registry63print("ASSET RENDER SCRIPT SET.")64############################################################################65#for loop to iterate through list of assets66#Array of character model load statements.67characters = [] 68#update with daz script rel file paths69characters.append("People/Genesis 2 Male/Genesis 2 Base Male.duf")70characters.append("People/Genesis 2 Female/Genesis 2 Base Female.duf")71characters.append("People/Genesis 3 Male/Genesis 3 Male.duf")72characters.append("People/Genesis 3 Female/Genesis 3 Female.duf")73characters.append("People/Genesis 8 Male/Genesis 8 Basic Male.duf")74characters.append("People/Genesis 8 Female/Genesis 8 Basic Female.duf")75#start from currentPos (calculated above) in array and iterate through each item76for x in range (currentPos, len(assetArray)): #arrayLength77 #time.sleep(60.0)78############################################################################79 #set relative path of current iteration80 relFilePath = assetArray[x] #set relative file path for render81 relFilePath = relFilePath.strip()82 fileName = os.path.basename(relFilePath)83 fileName = fileName.replace('.duf', '')84 fileName = fileName.strip()85 print(fileName)86############################################################################87 #check relative file path for acceptable file extensiosn88 if '.duf' in relFilePath:89 print('DUF IN FILENAME')90 ############################################################################91 #update script to render asset with relative file path92 fileIn = open("C:/Daz 3D/Applications/Data/DAZ 3D/My DAZ 3D Library/Scripts/Shortt/RenderAsset.txt", "rt")93 update = fileIn.read()94 #Update properties within script95 update = update.replace('FILEPATH', relFilePath)96 update = update.replace('FILENAME', fileName)97 ############################################################################98 #TIME TO START LOOKING AT LOADING THE NECESSARY CHARACTER99 ############################################################################100 #IF RelFilePath Contains "MALE" then load required MALE or feMALE character101 if "male" in relFilePath:102 ###########################################################################103 #Start checking RelFilePath for containing Genesis Male/Female 2/3/8 keywords104 #print("in") #test105 106 #Start with an array and iterate through it until correct char statement is found?107 #replacing keyword in renderAssets.txt to load character model108 if "Genesis 2 Male" in relFilePath:109 print("Load genesis 2 male character")110 update = update.replace('//LOADCHAR', characters[0])111 elif "Genesis 2 Female" in relFilePath:112 print("Load genesis 2 female character")113 update = update.replace('//LOADCHAR', characters[1])114 elif "Genesis 3 Male" in relFilePath:115 print("Load genesis 3 male character")116 update = update.replace('//LOADCHAR', characters[2])117 elif "Genesis 3 Female" in relFilePath:118 print("Load genesis 3 female character")119 update = update.replace('//LOADCHAR', characters[3])120 elif "Genesis 8 Male" in relFilePath:121 print("Load genesis 8 male character")122 update = update.replace('//LOADCHAR', characters[4])123 elif "Genesis 8 Female" in relFilePath:124 print("Load genesis 8 female character")125 update = update.replace('//LOADCHAR', characters[5])126 127 fileIn.close()128 #Open and write script updates to file129 fileOut = open("C:/Daz 3D/Applications/Data/DAZ 3D/My DAZ 3D Library/Scripts/Shortt/RenderAsset.dsa", "wt")130 fileOut.write(update)131 fileIn.close()132 fileOut.close()133 #Check for Renderfolder, Create if not exist.134 renderDirectory = "C:/Daz 3D/Applications/Data/DAZ 3D/AssetRender/Renders"135 renderedFile = renderDirectory + "/" + fileName136 if not os.path.exists(renderDirectory):137 os.makedirs(renderDirectory)138 #time.sleep(10)139 140 print("ABOUT TO RENDER")141 #time.sleep(10)142 ############################################################################143 #open daz studio144 dazStart = "C:/Daz 3D/Applications/64-bit/DAZ 3D/DAZStudio4/DAZStudio.exe"145 #Starting daz studio 146 subprocess.Popen([dazStart])147 #print("Daz running")148 renderCount = 0149 renderFound = False150 while(renderCount < 6): #60 time limit to open and render file before Daz is closed. Items not rendered added to error list151 if os.path.isfile(renderedFile):152 # Iterate over all running process153 for proc in psutil.process_iter():154 try:155 # Get process name & pid from process object.156 processName = proc.name()157 #processID = proc.pid #not required.158 #killing process from task manager to ensure no conflict with relaunching Daz Studio159 procname = "DAZStudio.exe"160 if proc.name() == procname:161 proc.kill()162 except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):163 pass164 165 renderFound = True166 break167 else:168 renderCount+=1169 time.sleep(10)170 #time.sleep(100) #allow 60 seconds for the render171 #store relative file path of files not rendered172 if(renderFound == False):173 file = open(directory + '/' + 'renderErrors.txt', 'a') #create file and record relative file paths of renders not created.174 file.write(relFilePath + "\n") 175 file.close()176############################################################################177 #open daz character178 #done in daz studio script179############################################################################180 #load daz asset181 #done in daz studio script182############################################################################183 #render asset and save184 #done in daz studio script185############################################################################186 #check if current progress location file exists187 #update file progress with relative file path of current asset being rendered.188 file = open(progressFilePath, 'r+')189 file.truncate(0) #clear out file190 file.close()191 with open(progressFilePath, 'a') as file:192 file.write(relFilePath) #write most recent file worked on193 file.close()194 #Kill Daz process195 for proc in psutil.process_iter():196 try:197 # Get process name & pid from process object.198 processName = proc.name()199 #processID = proc.pid #not required.200 #killing process from task manager to ensure no conflict with relaunching Daz Studio201 procname = "DAZStudio.exe"202 if proc.name() == procname:203 proc.kill()204 except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):205 pass206############################################################################207#set the daz studio script that runs on launch to empty208reg = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) #open the registry209sKey = winreg.OpenKey(reg, "SOFTWARE\DAZ\Studio4", 0 , winreg.KEY_ALL_ACCESS | winreg.KEY_WOW64_64KEY) #get the element to be updated210newPath = "" #Resetting the Script to load on launch to NULL211winreg.SetValueEx(sKey, 'StartupScene', '0' , winreg.REG_SZ, newPath) #set the new value212winreg.CloseKey(sKey) #close the value213winreg.CloseKey(reg) #close the registry 214############################################################################...

Full Screen

Full Screen

SDfile.py

Source:SDfile.py Github

copy

Full Screen

1import time2import os.path3from Signal import Signal4#Class that represents a csv file on the SDcard5#Each line represents a row in the table6class SDfile(file):7 f = ""8 relfilePath = "EMPTY"9 __fileExtension = ".csv"10 __currentDate = ""11 __locationID = ""12 def __init__(self, relativePath, location):13 self.relfilePath = relativePath14 self.setCurrentDate(time.strftime("%d_%m_%Y"))15 self.__locationID = location16 filePathBlack = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "black" + self.__fileExtension17 filePathGreen = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "green" + self.__fileExtension18 filePathBlue = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "blue" + self.__fileExtension19 filePathGrey = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "grey" + self.__fileExtension20 self.quickInit(filePathBlack)21 self.quickInit(filePathGreen)22 self.quickInit(filePathBlue)23 self.quickInit(filePathGrey)24 25 def getCurrentDate(self):26 return self.__currentDate27 def isCurrentDate(self, date):28 return self.__currentDate == date29 30 def setCurrentDate(self, date):31 self.__currentDate = date32 33 #CREATE and init the file with headers34 def quickInit(self, filePath):35 headers = "ID,Location,Date,Time"36 file = open(filePath, 'w+')37 file.write(headers + '\n')38 file.close()39 #opens the file, write the string to end of file, closes file40 def quickAppend(self, target):41 self.f = open(self.relfilePath + self.getCurrentDate + self.__fileExtension, 'a')42 self.f.write(target)43 self.f.close()44 #opens the file, writes each string in the buffer to the file, closes file45 #TODO need to edit the filePath to include the bin color, not the signal46 def quickAppendBuffer(self, target):47 date = time.strftime("%d_%m_%Y") #get current date48 if not self.isCurrentDate(date): #check if the date has changed49 self.setCurrentDate(date);50 #create file according to date, location and bin color51 filePathBlack = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "black" + self.__fileExtension;52 filePathGreen = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "green" + self.__fileExtension;53 filePathBlue = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "blue" + self.__fileExtension;54 filePathGrey = self.relfilePath + self.__currentDate + "_" + self.__locationID + "_" + "grey" + self.__fileExtension;55 if not os.path.isfile(filePathBlack): #create a new file if new date56 self.quickInit(filePathBlack);57 if not os.path.isfile(filePathGreen): #create a new file if new date58 self.quickInit(filePathGreen);59 if not os.path.isfile(filePathBlue): #create a new file if new date60 self.quickInit(filePathBlue);61 if not os.path.isfile(filePathGrey): #create a new file if new date62 self.quickInit(filePathGrey);63 currentFileBlack = open(filePathBlack, 'a');64 currentFileGreen = open(filePathGreen, 'a');65 currentFileBlue = open(filePathBlue, 'a');66 currentFileGrey = open(filePathGrey, 'a');67 for line in target:68 color = Signal.parseSignal(line)[0];69 if not color:70 return;71 if color == "black":72 print("TEST... Printing color: " + color + " to the filepath: " + filePathBlack);73 currentFileBlack.write(line + '\n');74 if color == "green":75 print("TEST... Printing color: " + color + " to the filepath: " + filePathGreen);76 currentFileGreen.write(line + '\n');77 if color == "blue":78 print("TEST... Printing color: " + color + " to the filepath: " + filePathBlue);79 currentFileGreen.write(line + '\n');80 if color == "grey":81 print("TEST... Printing color: " + color + " to the filepath: " + filePathGrey);82 currentFileGreen.write(line + '\n');83 84 currentFileBlack.close();85 currentFileGreen.close();86 currentFileBlue.close();87 currentFileGrey.close();88 #open file, read everything, close file, return result89 #TODO need to edit the filePath to include the bin color, not the signal90 def quickRead(self, filePath):91 result = []92 self.f = open(filePath, 'r')93 for line in self.f:94 editedLine = line.split('\n')95 result.append(editedLine[0])96 self.f.close()97 return result98 99 #Reads the specified line and returns an array of strings where each entry represents a column100 def readLine(self,number):101 self.f = open(self.relfilePath + self.getCurrentDate + self.__fileExtension, 'r')102 count = 0103 result = []104 for line in self.f:105 count = count + 1106 if count == number:107 line = line.strip() #remove whitespace108 result = line.split(",")109 break110 self.f.close()111 return result112 113 #Probably don't need to implement this114 #Takes as input which column to search under, and what you want to search for.115 def getLinesByID(self, column, searchString):116 print "not implemented yet"...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful