load variables from a text file


#1

hello everyone, I need your help.
As indicated in the title, I want to load variables from a text file. I’m writing a single script.
At first, I generate a text file “C:/tmp/variable.txt” , (with a fopen) in which there is this:

string $VARMAX[] = {“nurbsSphere1”,“pCube1”,“nurbsCone2”};

secondly, I load it:
source “C:/tmp/variable.txt”;
print $VARMAX;

it is now that the problem happens. If my file “C:/tmp/variable.txt” doesn’t yet exist, Maya will tell me ‘Cannot find file’. Logic.

So I try to put the command in a ‘evalEcho’,

pause -sec 1;
evalEcho “source “C://xdk//variable.txt”;”;
print $VARMAX;

I have this message: // Error: Line 3.14: “$VARMAX” is an undeclared variable. //
as if it was a procedure.

I need to have this text file to use it instantly or later.


#2

Couldn’t you simply check for the existence of the file and then decide to use the variable or not?
The function “filetest” seems to do this job.

I encourage you to use python for these things. Its module structure makes it very much easier to split files. And you can do something like:

try:
	fileHandle = open("myFile.txt", "r")
except:
	print "Failed to load"
	return

What makes error handling very much easiert than in mel


#3

thank you haggi for you help. However i have 300 lines of mel and I don’t know yet python.


#4

Learn it! Our amount of code is very much smaller since we switched to python and it is better maintainable.


#5

I also recommend Python, but in Mel I think you can check if a file exists with the command filetest.

string $tempFile = “C:\file.txt”;
filetest -r $tempFile;


#6

im giving a other vote for the python also sourcing a script to get more variables to use into the global scope isn’t exactly the most reliable way to go about things. If working with python you can easily use its json support to save variables and objects to files and re-read them into memory when ever you want.


import json

file_path = r'E:\chris\Desktop\vars.json'

# Dump Data to Json File
varimax = ["nurbsSphere1", "pCube1", "nurbsCone2"]
with open(file_path, 'w') as f:
	json.dump(varimax, f, sort_keys=True, indent=4)

# Load Data from json file
try:
	with open(file_path, 'r') as f:
		json_data = json.load(f)
	print json_data
except IOError:
	print "File does not Exist"


#7

ok, thank. I’ll try to learn python and convert my script.