I noticed a strange thing in Maya. I would like to know if you guys got the same problem or if I am doing something wrong?
There is the cmds.file command. The documentation says it got a "shortName" flag which should return the currently opend scenename without the complete path.
cmds.file(query = True, shortName = True)
# Error: RuntimeError: file <maya console> line 1: Flag cannot be queried. #
Also the doc. says that shortName is a queryable flag.
I also tried to just use the sceneName flag which should return the complete path of the currently opend file. Which indeed it does. But when I set it to "False" it gives me the same error you saw above.
This happens on Maya 2016 and Maya 2017.
The doc: http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/CommandsPython/file.html#flagshortName
Thanks for reading and have a nice day!
I'm not sure if you tried the command in the right way, but what the documentation says is:
When used with a main query flag it indicates that the file name returned will be the short name
So, in this situation the main query flag could be sceneName and then the shortName can be specified, to get just the filename.
import maya
print maya.cmds.file(query=True, sceneName=True, shortName=True)
Anyway, if you want to have a little more control over the specific path manipulation, may I suggest you to use the python os module? Or even better the os.path module?
Related
I'm trying to determine if a set of mesh nodes is currently visible or not. Using pymel and isVisible() works, but it's a huge performance hit.
Looking through the documentation, I found something that would (hopefully) solve my problem, the flag testVisibility on the Command hide.
According to the documentation the flag command will return a value that tells me if the specified nodes are visible or not.
The problem is, that flag doesn't exist.
import maya.cmds as cmds
cmds.sphere(name='testsphere')
cmds.hide('testsphere', testVisibility = True)
Gives an error
# Error: Invalid flag 'testVisibility'
# Traceback (most recent call last):
# File "<maya console>", line 4, in <module>
# TypeError: Invalid flag 'testVisibility' #
Same thing with the shortname of the flag "tv", as well as doing the whole thing in MEL: hide -testVisibility;.
The documentation includes this flag since Maya 2016. This is also the Maya version that I am using currently (more specifically, Maya 2016 SP5). Using the built-in link to the python documentation I arrive at the same documentation as I posted above. Looking through the changelog of SP6 doesn't mention anything of it either, so I assume it won't solve my problem.
I tried the same command on Maya 2017 and it works. That won't help me much though because that's not the Maya version that our team uses currently.
I can't contact Autodesk support because I'm not a subscriber (thanks autodesk, great help).
So my questions are:
is there something that I'm missing/that I overlooked? Are these flags only implemented in some kind of super duper developer plugin? Do Maya versions only use the API of the previous versions or something?
is there a way to check if a command has a flag, without try-catching it?
any workarounds that are not as performance draining as the pymel route I mentioned above?
You're right. I also tried tv flag for hide command and it definitely doesn't work.
Try setter/getter:
import maya.cmds as cmds
cmds.sphere(name="testsphere")
cmds.setAttr("testsphere.visibility", False)
cmds.getAttr("testsphere.visibility")
I tested it in Maya 2016/2018.
# Result: False #
I figured out the zip code in same line out. It's sys.argv[1], I had other code I neglected to comment out when trying out [1] that gave me the error. All I need help with now is getting weather.py to run without having to call the whole file path.
I will preface with I'm not very experienced with python and may get certain names wrong or think something might work that obviously doesn't, bear with me I tried to word this to make as much sense as possible.
So I need to run a program using the command line. The program is complete and 100% functioning when ran in PyDev. The program is called weather.py, and what needs to trigger it in cmd is
python weather.py (5 digit zip)
I cannot get the program to run using just 'python weather.py' first off. I have added C:\python27 to PATH as well as C:\python27\python.exe (not sure if that does anything). Getting the .py to run via those two keywords doesn't seem to work with what I've tried. I also need to be able to add a zip code to the same line to trigger the program. I was told about
zipcode = sys.argv[0]
to allow the zip code to be automatically initialized as a variable, but I get
IndexError: list index out of range
when I run the program using
python C:\python27\weather.py
I tried replacing 0 with 1 or 2 because I'm unfamiliar with .argv but neither of those worked either. Any help getting the program to run using just python weather.py OR getting the zip code input to function on the same line is greatly appreciated.
Make sure you import sys in your code.
import sys
zipCode = sys.argv[1]
and actually provide an argument
EDIT:
For clarity, if sys was not imported, you would get NameError and not an IndexError. Additionally, when passing args in from the command line, the indexing actually begins at 0 where sys.argv[0] is always the program name and the provided args begin at 1. So, in this case, the zip code would be at sys.argv[1]
EDIT2:
variable name to avoid using reserve words :)
I am very new to python, but I have written a simple python script tool for automating the process of updating mosaic datasets at my job. The tool runs great, but sometimes I get the dreaded 9999999 error, or "the geodatase already exists" when I try to overwrite the data.
The file structure is c:\users\my.name\projects\ImageryMosaic\Alachua_2014\Alachua_2014_mosaic.gdb. After some research, I determined that the lock was being placed on the FGDB whenever I opened the newly created mosaic dataset inside of the FGDB to check for errors after running the tool. I would like to be able to overwrite the data instead of having to delete it, so I am using the arcpy.env.overwriteOutput statement in my script. This works fine unless I open the dataset after running the tool. Since other people will be using this tool, I don't want them scratching thier heads for hours like me, so it would be nice if the script tool could look for the presence of a .Lock file in the geodatabase. That way I could at least provide a statement in the script as to why the tool failed in lieu of the unhelpful 9999999 error. I know about arcpy.TestSchemaLock, but I don't think that will work in this case since I am not trying to place a lock and I want to overwrite the FGDB, not edit it.
Late but this function below will check for lock files in given (gdb) path.
def lockFileExist(path = None):
if path == None:
import traceback
raise Exception("Invalid Path!")
else:
import glob
full_file_paths = glob.glob(path+"\\*.lock")
for f in full_file_paths:
if f.endswith(".lock"):
return True
return False
if lockFileExist(r"D:\sample.gdb"):
print "Lock file found in gdb. Aborting..."
else:
print "No lock files found!. Ready for processing..."
I have a program where I am creating a multitude of LaTeX files one by one. It is important when creating these LaTeX files to check that they can actually compile to a .pdf without error.
To do so it uses subprocess.call(['pdflatex', '-halt-on-error', tex_file_name]).
Which returns 0 on a successful compile from a .tex to a .pdf, and a 1 otherwise.
The problem I am having is that the only circumstance under which this line of code does not do what I think it should do, is when py.test runs it. If I run this code from an interpreter, or running a script from the command line, it works. But py.test doesn't.
When py.test errors, it leaves behind a log file created by pdflatex, which has this error in it:
{c:/texlive/2012/texmf-var/fonts/map/pdftex/updmap/pdftex.map
!pdfTeX error: pdflatex.exe (file c:/texlive/2012/texmf-var/fonts/map/pdftex/up
dmap/pdftex.map): fflush() failed (Bad file descriptor)
==> Fatal error occurred, no output PDF file produced!
I am hazarding a guess here that py.test is doing some thing with the .tex file prior to pdflatex being able to compile it. But I don't know what.
Temporary files and directories are talked about in the py.test docs. I don't know if they are relevant to my problem, but I have only played around with them briefly.
In case you want to look at the code, a test case looks like this:
from a import Foo
from b import Tree
from latex_tester import latex_tester
def test_Foo():
q1 = foo.Foo()
latex_tester(Tree(1, q1))
and latex_tester looks like this:
import uuid
import os
import subprocess
def latex_tester(tree):
""" Test whether latex is compilable to a PDF.
"""
full_path = r'some_path'
uid = str(uuid.uuid1())
file_name = os.path.join(full_path, 'test' + uid + '.tex')
with open(file_name, 'w') as f:
_write_tree(f, tree)
retcode = subprocess.call(['pdflatex', '-halt-on-error', file_name])
if retcode != 0:
raise RuntimeError("This latex could not be compiled.")
Oddly enough, using 'xelatex' instead of 'pdflatex' makes things work as normal.
For any future readers - I have TeXworks installed which presumably installed both these tools. I don't know if xelatex influences the final pdf produced. It seems to be producing a good .pdf
Anyway, I made this answer to my own question since there doesn't seem to be anything else coming and it certainly solved my problem.
I had exactly the same problem.
I'm using C# as programming language for creating the .tex documents and it crashed during pdflatex when I included a image into the pdf.
And it worked if i started it manually...
Error:
pdfTeX warning: pdflatex
!pdfTeX error: pdflatex (file <linktoFile>/file.pdf): fflush() failed (Bad file descriptor)
Unfortunately xelatex didn't work either so I searched and eventually stumbled upon it.
Basically the error happened for me at this line:
string tex = tex.Replace("\uFFFD\uFFFDMEMNAME\uFFFD\uFFFD", user.Surname)
Here user.Surname was null.
When the tex string is saved into the file it mysteriously remembers the null and pdflatex crashes somewhere completely different. If you on the other hand start pdflatex on the same file again manually the null is gone and it works.
The whole mess went away when I entered a Surname and it works now from the program.
Maybe this will help someone with the same problem.
I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:
def load(s):
# Do some stuff
return something
In order to call this function I have to type
>>> load('something')
I would rather be able to simply type:
>>> load something
I am running Python with readline support, so I know there exists some programmability there, but I don't know if this sort of thing is possible using it.
I attempted to get around this by using the InteractivConsole and creating an instance of it in my startup file, like so:
import code, re, traceback
class LoadingInteractiveConsole(code.InteractiveConsole):
def raw_input(self, prompt = ""):
s = raw_input(prompt)
match = re.match('^load\s+(.+)', s)
if match:
module = match.group(1)
try:
load(module)
print "Loaded " + module
except ImportError:
traceback.print_exc()
return ''
else:
return s
console = LoadingInteractiveConsole()
console.interact("")
This works with the caveat that I have to hit Ctrl-D twice to exit the python interpreter: once to get out of my custom console, once to get out of the real one.
Is there a way to do this without writing a custom C program and embedding the interpreter into it?
Edit
Out of channel, I had the suggestion of appending this to the end of my startup file:
import sys
sys.exit()
It works well enough, but I'm still interested in alternative solutions.
You could try ipython - which gives a python shell which does allow many things including automatic parentheses which gives you the function call as you requested.
I think you want the cmd module.
See a tutorial here:
http://wiki.python.org/moin/CmdModule
Hate to answer my own question, but there hasn't been an answer that works for all the versions of Python I use. Aside from the solution I posted in my question edit (which is what I'm now using), here's another:
Edit .bashrc to contain the following lines:
alias python3='python3 ~/py/shellreplace.py'
alias python='python ~/py/shellreplace.py'
alias python27='python27 ~/py/shellreplace.py'
Then simply move all of the LoadingInteractiveConsole code into the file ~/py/shellreplace.py Once the script finishes executing, python will cease executing, and the improved interactive session will be seamless.