Is it possible to use the maya.cmds instead of using any maya API to load/import in a file format in which it is not part of Maya file types?
I have tried googling but to no avail results other than the fileDialog command in Maya, otherwise it would means I will need to implement maya API (where I totally do not have any experiences with it)
I tried the following:
multipleFilters = "chan (*.chan)"
fileList = cmds.fileDialog2(fileMode=1, fileFilter=multipleFilters, dialogStyle=2)
if not fileList:
# return or print something or bail out early
filename = fileList[0]
cmds.file(filename, i=True)
Instead I keep getting the following error:
# Error: Unrecognized file.
# Traceback (most recent call last):
# File "<maya console>", line 3, in <module>
# RuntimeError: Unrecognized file. #
Any ideas?
cmds.file only works for files with translators that are registered via the API, either in Python or C++.
You can, however, easily write python (or even mel) scripts which read files off disk and create stuff in your scenes. You can use cmds.fileDiialog2 to present a file dialog to the user to pick file off disk, but it will be up to you to read the file.
multipleFilters = "chan (*.chan)"
fileList = cmds.fileDialog2(fileMode=1, fileFilter=multipleFilters, dialogStyle=2)
with open (fileList[0], 'rt') as filehandle:
for line in filehandle:
print line # or do something useful with the data
Related
I am trying to iteratively process a list of compressed files. Each compressed file contains a large number of XML documents, some even contain up to 92,000 XML documents. Inside the nested loop, I am iterating over the list of extracted XML documents and pulling specific XML field values from each XML document. The problem is that I keep running into following issue after 5 minutes of the script running: [Errno 23] Too many open files in system.
When I uncomment the call to ‘parse_xml_files’ from the main function below, the script goes to completion without any issues. I am confused what is causing this issue since the files are being read using a context manager which should by itself close each XML files after they have been processed. May be I am overlooking something.
Many solutions on stackoverflow seems to be revolving around permanently increasing the limit of number of open files using ‘ulimit -a’. However, this solution does not work for me as I am dealing with such as a large number of files.
Any insight into this is greatly appreciated!
from os import system
from os import walk, path as ospath, makedirs
from bs4 import BeautifulSoup
from os import walk
def find_all_xml_files(path):
file_queue = []
for (dirpath, _, filenames) in walk(path):
if len(filenames) == 0:
continue
for filename in filenames:
if filename.endswith('.xml'):
file_queue.append(f'{dirpath}/{filename}')
else:
# Ignore unknown file formats
pass
return file_queue
def parse_xml_files(xml_files):
for xml_file in xml_files:
with open(xml_file, 'r') as f:
handler = f.read()
xml_doc = BeautifulSoup(handler, 'lxml')
""" And then extract and store various parts of the XML document """
def main():
# Retrieve list of files to process
compressed_files = get_files_to_process()
for compressed_file in compressed_files:
temp_folder = f'.temp' # Temporary directory to store extracted contents
# Create temporary storage file
makedirs(temp_folder)
# Unzip the compressed file
unzip_cmd = f'unzip -o {compressed_file} -d {temp_folder}'
system(unzip_cmd)
# Retrieve list of extracted XML files for parsing
xml_files = find_all_xml_files(temp_folder)
parse_xml_files(xml_files) # Commenting this line helps the script go to completion without any errors
# Delete temporary direcory and its content
delete_cmd = f'rm -r {temp_folder}'
system(delete_cmd)
main()
Update:
This is the Traceback:
Traceback (most recent call last):
File "main.py", line 36, in <module>
File "main.py", line 30, in main
File "main.py", line 8, in main
OSError: [Errno 23] Too many open files in system: '.temp/xyz.xml'
After the above traceback is shown, I am having to reboot my entire system because everything running on my laptop becomes unresponsive.
I am using Python pdftables to fetch table data from pdf and i followed the instructions as give in git
https://github.com/drj11/pdftables
but when i run the code
filepath = 'tests.pdf'
fileobj = open(filepath,'rb')
from pdftables.pdf_document import PDFDocument
doc = PDFDocument.from_fileobj(fileobj)
i get error like this
File "<stdin>", line 1, in <module>
File "pdftables/pdf_document.py", line 53, in from_fileobj
raise NotImplementedError
can any anyone help me out in this problem
If you look at the file implementing the from_fileobj function you can see the following comment:
# TODO(pwaller): For now, put fh into a temporary file and call
# .from_path. Future: when we have a working stream input function for
# poppler, use that.
If I understand it correctly you should instead use the from_path function as from_fileobj is not implemented yet. This is easy with your current code:
filepath = 'tests.pdf'
from pdftables.pdf_document import PDFDocument
doc = PDFDocument.from_path(filepath)
I am trying to pass an argument from batch file to my python file.
I followed the steps given in these two links:
Passing Argument from Batch File to Python
Sending arguments from Batch file to Python script
Here is a part of my python file where I'm trying to pass argument:
def main(argv):
imapServ = 'imap.gmail.com'
filename = 'TestRunLog.log'
attachment = open("{} {}".format(argv[0], filename), 'rb')
....##rest of the code
import sys
try:
if __name__ == '__main__':
print 'go ahead'
main(sys.argv[:1])
except ImportError:
print 'hi'
Also, here is the part of batch file which I'm using to send argument to the Python file:
c:\python27\python.exe C:\Users\abcd\Documents\automation\testsendemail.py %%myhome%\Documents\automation\Testresults\%resultDir%
pause
Above, %resultDir% is the variable which is generated based on timestamp.
Here is the output:
go ahead
Traceback (most recent call last):
C:/Users/abcd/Documents/automation/testsendemail.py\TestRunLog.log
File "C:/Users/abcd/Documents/automation/testsendemail.py", line 44, in <module>
main(sys.argv[:1])
File "C:/Users/abcd/Documents/automation/testsendemail.py", line 25, in main
attachment = open("{} {}".format(argv[0], filename), 'rb')
IOError: [Errno 2] No such file or directory: 'C:/Users/abcd/Documents/automation/testsendemail.py TestRunLog.log'
I followed lots of stackoverflow questions regarding this issue but still I'm unable to run. Not sure where the mistake is.
The issue is related on how python works with argv.
In this scenario, when you run:
main(sys.argv[:1]) # (["C:\Users\abcd\Documents\automation\testsendemail.py"])
you actually get only the first arguments passed to the python script, which is the current script location.
To get all the arguments but the first, you must fix that array filter:
main(sys.argv[1:]) # ["%%myhome%\Documents\automation\Testresults\%resultDir%"])
Note that the second filter will also include any other arguments that you might add to the command line.
Also, as a side note. You should consider using the STD lib to join the paths.
It should be something like this:
from os.path import join
(...)
filename = 'TestRunLog.log'
attachment = open(join(argv[0], filename), 'rb')
I've been adapting an old piece of code to be Python 3 compliant and I came across this individual script
"""Utility functions for processing images for delivery to Tesseract"""
import os
def image_to_scratch(im, scratch_image_name):
"""Saves image in memory to scratch file. .bmp format will be read
correctly by Tesseract"""
im.save(scratch_image_name, dpi=(200, 200))
def retrieve_text(scratch_text_name_root):
inf = file(scratch_text_name_root + '.txt')
text = inf.read()
inf.close()
return text
def perform_cleanup(scratch_image_name, scratch_text_name_root):
"""Clean up temporary files from disk"""
for name in (scratch_image_name, scratch_text_name_root + '.txt',
"tesseract.log"):
try:
os.remove(name)
except OSError:
pass
On the second function, retrieve_text the first line fails with:
Traceback (most recent call last):
File ".\anpr.py", line 15, in <module>
text = image_to_string(Img)
File "C:\Users\berna\Documents\GitHub\Python-ANPR\pytesser.py", line 35, in image_to_string
text = util.retrieve_text(scratch_text_name_root)
File "C:\Users\berna\Documents\GitHub\Python-ANPR\util.py", line 10, in retrieve_text
inf = file(scratch_text_name_root + '.txt')
NameError: name 'file' is not defined
Is this a deprecated function or another problem alltogether? Should I be replacing file() with something like open()?
In Python 2, open and file are mostly equivalent. file is the type and open is a function with a slightly friendlier name; both take the same arguments and do the same thing when called, but calling file to create files is discouraged and trying to do type checks with isinstance(thing, open) doesn't work.
In Python 3, the file implementation in the io module is the default, and the file type in the builtin namespace is gone. open still works, and is what you should use.
You can do what the documentation for file() suggests -
When opening a file, it’s preferable to use open() instead of invoking this constructor directly.
You should use open() method instead.
I'm attempting to write a very simple script that counts the number of entries/files a given ZIP file has, for some statistics.
I'm using the zipfile library, and I'm running into this problem where the library appears not to support .zipx format.
bash-3.1$ python zipcount.py t.zipx
Traceback (most recent call last):
File "zipcount.py", line 10, in <module>
zipCount(file)
File "zipcount.py", line 5, in zipCount
with ZipFile(file, "r") as zf:
File "c:\Python34\lib\zipfile.py", line 937, in __init__
self._RealGetContents()
File "c:\Python34\lib\zipfile.py", line 978, in _RealGetContents
raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file
Googling for help reveals that the zipx format is not the same as zip, and so maybe I shouldn't be expecting this to work. Further googling though fails to bring up a library that actually can deal with zipx. Searching stack overflow didn't find much either.
I can't possibly be the only person who wants to manipulate zipx files in python, right? Any suggestions?
chilkat might work for this. It's not a free library but there is a 30 day trial. Here is an example from http://www.example-code.com/python/ppmd_compress_file.asp:
import sys
import chilkat
compress = chilkat.CkCompression()
# Any string argument automatically begins a 30-day trial.
success = compress.UnlockComponent("30-day trial")
if (success != True):
print "Compression component unlock failed"
sys.exit()
compress.put_Algorithm("ppmd")
# Decompress back to the original:
success = compress.DecompressFile("t.zipx", "t")
if (success != True):
print compress.lastErrorText()
sys.exit()
print "Success!"
The API documentation: http://www.chilkatsoft.com/refdoc/pythonCkCompressionRef.html
There is no direct python package to unzip the zipx files in python.
So, One simple way to unzip it is using subprocess and winzip application. Please find the below code.
import subprocess
command = "C:\Program Files\WinZip\wzunzip.exe" "D:\Downloads\hello.zipx" "D:\unzip_location"
subprocess.run(command, shell=True, timeout=120)