import a custom python script to maya - python-2.7

I am currently trying to import my custom script into maya. I have found this example. My gole is to be able to edit script externally, reload it on each click.
I have tried the following script in python console, and it seems to work. Unfortunately it give me some error when I click the custom button in maya.
So this is the script of my custom button in maya
import sys
import os
def psource(module):
file = os.path.basename( module )
dir = os.path.dirname( module )
toks = file.split( '.' )
modname = toks[0]
# Check if dirrectory is really a directory
if( os.path.exists( dir ) ):
# Check if the file directory already exists in the sys.path array
paths = sys.path
pathfound = 0
for path in paths:
if(dir == path):
pathfound = 1
# If the dirrectory is not part of sys.path add it
if not pathfound:
sys.path.append( dir )
# exec works like MEL's eval but you need to add in globals()
# at the end to make sure the file is imported into the global
# namespace else it will only be in the scope of this function
exec ('import ' + modname) in globals()
# reload the file to make sure its up to date
exec( 'reload( ' + modname + ' )' ) in globals()
# This returns the namespace of the file imported
return modname
# When you import a file you must give it the full path
psource( '/The/correct/path/to/my/script/import_test_model.py' )
import_test_model.main()
while this is my custom script
def main():
print "funziona"
return
if __name__ == "__main__":
main()
this is error messages I'm getting
...
# When you import a file you must give it the full path
psource( '/Users/rostyslavkostyuk/Documents/developing/py_maya/import_test_model.py' )
import_test_model.main()
# Error: SyntaxError: file <string> line 1: invalid syntax #
# Error: invalid syntax #
# Error: invalid syntax #
# Error: invalid syntax #

I don't know what was the issue, but to solve it I just deleted the old button, and created the new one, and it started to work.

Related

Python 2.7 and PrettyTables

I am trying to get PrettyTables to work with the following script. I can get it almost to look right but it keeps separating my tables so it is printing 16 separate tables. I need all information in one table that I can sort. I appreciate all the help i can get.
import sys
import os
import datetime
import hashlib
import logging
def getScanPath(): #12
# Prompt User for path to scan
path = raw_input('Please enter the directory to scan: ')
# Verify that the path is a directory
if os.path.isdir(path):
return path
else:
sys.exit('Invalid File Path ... Script Aborted')
def getFileList(filePath):
# Create an empty list to hold the resulting files
pathList =[]
# Get a list of files, note these will be just the names of the files
# NOT the full path
simpleFileNameList = os.listdir(filePath)
# Now process each filename in the list
for eachFile in simpleFileNameList:
# 1) Get the full path by join the directory with the filename
fullPath = os.path.join(filePath, eachFile)
# 2) Make sure the full path is an absolute path
absPath = os.path.abspath(fullPath)
# 3) Make sure the absolute path is a file i.e. not a folder or directory
if os.path.isfile(absPath):
# 4) if all is well, add the absolute path to the list
pathList.append(absPath)
else:
logging.error('A Non-File has been identified')
# 5) Once all files have been identified, return the list to the caller
return pathList
def getFileName(theFile):
return os.path.basename(theFile)
def getFileSize(theFile):
return os.path.getsize(theFile)
def getFileLastModified(theFile):
return os.path.getmtime(theFile)
def getFileHash(theFile):
hash_md5 = hashlib.md5()
with open(theFile, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
# Main Script Starts Here
if __name__ == '__main__':
#Welcome Message
print "\nWelcome to the file scanner\n"
# prompt user for directory path
scanPath = getScanPath()
# Get a list of files with full path
scanFileList = getFileList(scanPath)
# Output Filenames
print "Files found in directory"
for eachFilePath in scanFileList:
fileName = getFileName(eachFilePath)
fileSize = getFileSize(eachFilePath)
lastModified = getFileLastModified(eachFilePath)
hashValue = getFileHash(eachFilePath)
fileModified = (datetime.datetime.fromtimestamp(lastModified))
from prettytable import PrettyTable
pTable = PrettyTable()
pTable.field_names = ["File Name", "File Size", "Last Modified", "Md5 Hash Value"]
pTable.add_row ([fileName, fileSize, fileModified, hashValue])
print (pTable)enter code here
This should show me one big table using all the values from a set directory that the user chooses. This will allow me to sort the table later using prettytables.
I have no experience with prettyTables, but I noticed you have lastModified and fileModified yet only fileModified is used for a column in your table. Are you sure pretty table doesn't have some kind of row limit?

What does: "error: invalid command 'bdist'" mean?

I'm trying to convert a python script into a standalone executable, and it stops at "error: invalid command 'bdist'"with both cx_freeze as well as with py installer.
I can not find what this error means, would you have any suggestions?
As requested in the comment, this is the main code, in Renaming_variables2 an external file is called, and if I don't add that file it gives an error. I think that implies exe runs at least untill that line. Then when I add the external file to it's requested location, that file-missing error is removed and the bdist error shows up. Without any line indication.
#Define variables
#Parameters:
import psutil
import os
import sys
import shutil
import time
print("the directory of the python installation = ", os.path)
print("the working directory of this project = ", os.getcwd())
print("the directory of this py = ", os.path.dirname(os.path.realpath(__file__)))
breaktime = 11
refresh_time = 2
nr_of_task_scheduler_commands = list()
for i in range(0,2):
nr_of_task_scheduler_commands.append(False)
name_check_md = "d.py"
convert_name_check_md = "Convert_d_py2exe.py"
path_name_check_md_and_conversion = "a/"
file_path = os.path.dirname(os.path.realpath(__file__))
file_path =file_path .replace('\\','/')
name_run_check = "ma.py"
convert_run_check = "Convert_s_py2exe.py"
path_run_check_and_conversion = "b/"
path_task = "task"
path_task_adm = "/adm"
name_original_task = "task.xml"
name_task = "task.xml"
temp_name_task = "taskq.xml"
adm_run_bat = "RunAsAdminConsole.bat"
output_adm= "/output_adm"
add_task_bat = "callrunasadminconsole4.bat"
import getpass
user_name = getpass.getuser()
import socket
domain = socket.getfqdn()
destination_path = "C:/out"
parent_output = 'output'
parent_dist = 'dist/'
#Not replaced below
name_check_md_exe = "ds.exe"
#Not replaced below
path_check_md_exe = "a/dist/"
name_run_check_exe = "dc.exe"
#Not replaced below
path_run_check_exe = "b/dist/"
#Not replaced below
path_min = "sx"
path_gmin = "dr"
md_output = "output.txt"
import getpass
print getpass.getuser()
#check if folder exists and if not, create it
if not os.path.exists(destination_path):
print destination_path + " is not an existing path"
# 1.0 if non-existant goto step 2
# 1.1 if existant: go to step 3.
# 2. read manual path from: "path.txt"
destination_path = raw_input("Please enter a new system path ")
# 3. feed path into Renaming_variables.py
# 4. run Renaming_variables.py
# Disable printing
def blockPrint():
sys.stdout = open(os.devnull, 'w')
import Renaming_variables2
# 5. run callerY.py
import caller5
os.chdir(file_path +'/'+ path_task+path_task_adm)
os.startfile("RunAsAdminConsole.bat")
#1.a #first delete destination file from /task if it exists
def deletion(file_path, old_file_name):
try:
# delete all files in folder
file_and_folder_path = os.path.join(file_path, old_file_name)
os.remove(file_and_folder_path)
except:
pass
deletion(file_path +'/'+ path_task,"RunAsAdminConsole.exe")
#1.b #then move file to /task
time.sleep(10)
shutil.move(file_path +'/'+ path_task+path_task_adm+output_adm+'/'+"RunAsAdminConsole.exe" , file_path +'/'+ path_task+'/')
os.chdir(file_path +'/'+ path_task+'/')
os.startfile("callrunasadminconsole4.bat")
However, I would like to stress that this question is not about solving that problem, this question is about the meaning of the following error message:
error: invalid command 'bdist'

Using gdal_calc multiple times within a Python Script, Issues with Visual C++ for Python 2.7

I've exhausted what I'm capable of currently regarding the script that I have posted below. I am unable to properly call gdal_calc.py with this script. I have received various error message regarding a lack of .dll files to a win32 error.
I have installed and reinstalled GDAL, however I continue to receive an error message that suggests I don't have osgeo, and I cannot install GDAL properly within my Python27 pathway because of an issue with Visual C++ for Python because I either don't have the proper .bat file OR I get this message.
fatal error C1083: Cannot open include file: 'cpl_port.h': No such file or directory
I would appreciate even a direction to be point in, because I am a novice and this is over my head.
Thanks,
import os
import sys
from osgeo import gdal
from gdalconst import *
import numpy as np
import math
import subprocess
from subprocess import call
import math
import PIL
from PIL import Image
# constants
gdalTranslate = r'C:\\Program Files (x86)\\GDAL\\gdal_translate.exe'
src = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA.img"
srcVH = r"C:\Users\jack\Desktop\RUA_FIL\IMG-VH-ALOS2110871010-160611-HBQR1.5RUA.img"
dstVH = r"C:\Users\jack\Desktop\New_Trash\vhFloat32-3.img"
dst = r"C:\\Users\jack\Desktop\\New_Trash\hvFloat32-3.img"
cmd = "-ot Float32 -of HFA" # hopefully this works
#gdalCalc = r'C:\Python27\ArcGIS10.4\Scripts\dist\gdal_calc.exe'
#hvFloat32 = r"C:\Users\jack\Desktop\New_Trash\hvFloat32-1.img"
#vhFloat32 = r"C:\Users\jack\Desktop\New_Trash\hvFloat32-1.img"
#prevName = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA"
#newName = r"C:\Users\jack\Desktop\RUA_FIL\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA.img"
#os.rename(prevName,newName)
# setting def
#def gdal_Translate (item):
#return item
hvfullCmd = ' '.join([gdalTranslate, cmd, gdal_Translate(src), gdal_Translate(dst)])
subprocess.Popen(hvfullCmd)
vhfullCmd = ' '.join([gdalTranslate,cmd,gdal_Translate(srcVH),gdal_Translate(dstVH)])
subprocess.Popen(vhfullCmd)
# Run gdal_calc.py for HV
try:
os.system('C:\Users\jack\Python\QGIS Python Scripts\ridofZs.py')
except:
print ("This isn't working")
sys.exit()
subprocess.call([sys.executable,'C:\Program Files (x86)\GDAL\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\hvFloat32.img', '--outfile=C:\Users\jack\Desktop\New_Trash\NEWCALCHV-2.img','--calc=A*(A>=1)'])
# Run gdal_calc.py for VH
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\vhFloat32.img', '--outfile=C:\Users\jack\Desktop\New_Trash\NEWCALCVH-2.img','--calc=A*(A>=1)'])
# Run gdal_calc.py to dB for HV
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\NEWCALCHV-2.img', '--outfile=C:\Users\jack\Desktop\New_Trash\HVindB.img','--calc=10*log10(power(A,2))-83'])
# Run gdal_calc.py to dB for HV
#subprocess.call([sys.executable, 'C:\OSGeo4W64\bin\gdal_calc.py', '-A', 'C:\Users\jack\Desktop\New_Trash\NEWCALCVH-2.img', '--outfile=C:\Users\jack\Desktop\New_Trash\VHindB.img','--calc=10*log10(power(A,2))-83'])
# Open Rasters using GDAL
hvRaster = gdal.Open("C:\\Users\\jack\\Desktop\\New_Trash\\hvFloat32.img")
vhRaster = gdal.Open("C:\\Users\\jack\\Desktop\\New_Trash\\vhFloat32.img")
# Get RasterBand
hvRasterBand = hvRaster.GetRasterBand(1)
vhRasterBand = vhRaster.GetRasterBand(1)
# Get Raster Mean
hvMean = hvRasterBand.GetStatistics(0,1)[2]
vhMean = vhRasterBand.GetStatistics(0,1)[2]
#### Maybe not needed
print hvMean
print vhMean
# calculate stDev
rasterList = (hvMean,vhMean)
stDev = np.std(rasterList)
#print stDev
if stDev >= 0.06:
print "The imagery isn't acceptable"
if stDev <= 0.06:
print "The imagery is acceptable"

Can't close file, being used by another process, windows error 32?

I'm trying to have a script that will automatically download files and install them in the correct directories. However When i try to delete the downloaded file after everything has been extracted correctly, I get an OS error that its being used by another process. I use with so the file should close correctly, but even if i put manual closes for source and zip_file it still gives this error. Does anyone know why?
It is most definitely being used by the python interpreter and not any other program, i tested this using "Unlocker". So my only conclusion is the file isn't closing after i open it.
# Downloads, updates, and installs the most recent version of flippy. Only tested on Windows operating systems.
import os
import shutil
import zipfile
import urllib
from os.path import expanduser
import maya.cmds as mc
import maya.mel as mel
download_dir = expanduser("~")
scripts_path = mc.internalVar(usd=True)
prefs_path = mc.internalVar(upd=True)
urllib.urlretrieve(r"https://drive.google.com/uc?export=download&id=0BwF-kFX824PuXzZVQmJja3JzNkE", r"%s/flippy.zip" %(download_dir))
with zipfile.ZipFile("%s/flippy.zip" %(download_dir)) as zip_file:
for member in zip_file.namelist():
with zip_file.open(member) as source:
filename = os.path.basename(member)
if filename == 'flippy.py' or filename == 'flippy_invert_attrs.txt':
target = file(os.path.join(scripts_path, filename), "wb")
copy = True
elif filename == 'flippy_icon.png':
target = file(os.path.join("%s/icons" %(prefs_path), filename), "wb")
copy = True
elif filename == 'shelf_NeoTools.mel':
target = file(os.path.join("%s/shelves" %(prefs_path), filename), "wb")
copy = True
elif filename == 'CHANGELOG.txt':
copy = False
for line in source:
print line
else:
copy = False
# copy file (taken from zipfile's extract)
if copy:
with source, target:
shutil.copyfileobj(source, target)
os.remove("%s/flippy.zip" %(download_dir))
This code gives the following error:
# Error: 32
# Traceback (most recent call last):
# File "<maya console>", line 40, in <module>
# WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'F:/My Documents/flippy.zip' #

Search for Files of a Specific Type

I'm using Python 2.7.2 and PyScriptor to create a script that I hope to use to first find a file of type (.shp) and then check to see if there is a matching file with the same name but with a (.prj) suffix. I'm stuck in the first part. I hope to share this script with others so I am trying to make the starting folder/directory a variable. Here's my script so far:
# Import the operating and system modules.
import os, sys
def Main():
# Retrieve the starting folder location.
InFolder = sys.argv[1]
#InFolder = "C:\\_LOCALdata\\junk"
os.chdir(InFolder)
print os.path.exists(Infolder)
print InFolder
# Begin reading the files and folders within the starting directory.
for root, dirs, files in os.walk(InFolder):
print os.path.exists(root)
for file in files:
print file
if file.endswith(".py"):
print os.path.join(root, file)
elif file.endswith(".xlsx"):
print os.path.join(root, file)
elif file.endswith(".shp"):
print "Shapefile present."
elif file.endswith(".txt"):
print "Text file present."
else:
print "No Python, Excel or Text files present."
return()
print "End of Script."
sys.exit(0)
if __name__ == '__main__':
sys.argv = [sys.argv[0], r"C:\_LOCALdata\junk"]
Main()
The only result I have gotten so far is:
*** Remote Interpreter Reinitialized ***
>>>
End of Script.
Exit code: 0
>>>
Any suggestions?
Layne
You're exiting your script before it even has a chance to get started!. Remove or indent these lines:
print "End of Script."
sys.exit(0)
Starting procedurally from the top (like python does), we:
Import libraries
Define the Main funcion.
Print a line, and immediately exit!
Your __name__ == '__main__' is never reached.
Oh man - duh. Thanks for the input. I did get it to work. The code searches for shapefiles (.shp) and then looks for the matching projection file (.prj) and prints the shapefiles that do not have a projection file. Here is the finished code:
# Import the operating and system modules.
import os, sys
def Main():
# Retrieve the starting folder location.
InFolder = sys.argv[1]
text = (InFolder + "\\" + "NonProjected.txt")
outFile = open(text, "w")
# Begin reading the files and folders within the starting directory.
for root, dirs, files in os.walk(InFolder):
for file in files:
if file.endswith(".shp"):
PRN = os.path.join(root,(str.rstrip(file,"shp") + "prj"))
if os.path.exists(PRN):
pass
else:
outFile.write((str(os.path.join(root,file))) + "\n")
print os.path.join(root,file)
else:
pass
outFile.close()
print
print "End of Script."
sys.exit(0)
return()
#================================================================================
if __name__ == '__main__':
sys.argv = [sys.argv[0], r"G:\GVI2Hydro"]
#sys.argv = [sys.argv[0], r"C:\_LOCALdata"]
#sys.argv = [sys.argv[0], r"U:"]
Main()