Guardar un nuevo script para conservar las variables para más adelanteHola,
Creé un script que realiza análisis de datos pero requiere varias entradas del usuario para configurarlo. Hay casos en los que quiero realizar un análisis similar más adelante, pero no necesito volver a ingresar todas mis configuraciones. El script principal ya puede leer variables existentes y autocompletar esos campos, por lo que si tengo alguna forma de guardar e importar esos valores predeterminados, estaré listo. Quiero poder tener múltiples configuraciones diferentes y no necesitar editar el script para crear uno nuevo.
Una idea era guardar una tabla con una columna de nombres de variables y una columna de sus valores, pero eso no funcionaba bien con diferentes tipos de variables (números, cadenas, listas).
Una idea que parece mejor es guardar otros archivos .jsl que contienen la configuración predeterminada para diferentes casos de uso en un espacio de nombres compartido y luego ejecutar el correspondiente antes de ejecutar mi script principal. Me gustaría poder crear el archivo de configuración desde mi script, en lugar de crearlo manualmente.
Encontré esta otra publicación sobre cómo guardar nuevos archivos jsl. https://community.jmp.com/t5/Discussions/how-do-you-create-a-new-script-file-from-jsl/td-p/34740
Parece que debería poder configurar una cotización JSL y luego sustituir los valores actuales de las variables en esa cotización, pero NameExpr no funciona para eso. Las cadenas se sustituyen sin comillas, las listas simplemente aparecen como Lista y los números se ignoran. ¿Existe algún pequeño cambio que haría que esto funcione o una mejor manera de lograr el mismo objetivo?
¡Gracias!
names default to here (1);
//namespace for the shared variables
If( !Namespace Exists( "TestNS" ), New Namespace( "TestNS" ) );
//the variables I want to save for later
TestNS:a = 5;
TestNS:b = "text";
TestNS:c = {1,2,3,4};
TestNS:d = {"a","b","c","d"};
//set up script to save as JSL
script = JSL Quote(
TestNS:a = a_dv;
TestNS:b = b_dv;
TestNS:c = c_dv;
TestNS:d = d_dv;
);
//substitute the dummy values for the current values... this isn't working
substitute Into (script, expr(a_dv), nameexpr (TestNS:a));
substitute Into (script, expr(b_dv), nameexpr (TestNS:b));
substitute Into (script, expr(c_dv), nameexpr (TestNS:c));
substitute Into (script, expr(d_dv), nameexpr (TestNS:d));
show(script);
//save script for later use
Save Text File( "$downloads\MyScript.jsl", script );Automatización y secuencias de comandosventanasRe: Guardar un nuevo script para conservar las variables para más adelanteNo estoy seguro de qué tan universal es esto, pero funciona en tu script simple.
names default to here (1);
//namespace for the shared variables
If( !Namespace Exists( "TestNS" ), New Namespace( "TestNS" ) );
//the variables I want to save for later
TestNS:a = 5;
TestNS:b = "text";
TestNS:c = {1,2,3,4};
TestNS:d = {"a","b","c","d"};
//set up script to save as JSL
script = expr(
TestNS:a = a_dv;
TestNS:b = b_dv;
TestNS:c = c_dv;
TestNS:d = d_dv;
);
//substitute the dummy values for the current values... this isn't working
substitute Into (script, expr(a_dv), nameexpr (TestNS:a));
substitute Into (script, expr(b_dv), nameexpr (TestNS:b));
substitute Into (script, expr(c_dv), nameexpr (TestNS:c));
substitute Into (script, expr(d_dv), nameexpr (TestNS:d));
// Move the arguments in the script to a character string
theScript = "";
i=1;
While( char(arg(script,i)) !="Empty()",
theScript = theScript || char(arg(script,i)) || ";";
i++;
);
show(script);
//save script for later use
Save Text File( "$downloads\MyScript.jsl", theScript );Re: Guardar un nuevo script para conservar las variables para más adelante¿Quizás haya considerado almacenar esos valores en una matriz asociativa? Probablemente sea más fácil de administrar y se puede guardar, por ejemplo, como JSON si es necesario.
Names Default To Here(1);
//namespace for the shared variables
If(!Namespace Exists("TestNS"),
New Namespace(
"TestNS"
)
);
//the variables I want to save for later
TestNS:settings = Associative Array();
TestNS:settings["a"] = 5;
TestNS:settings["b"] = "text";
TestNS:settings["c"] = [1 2 3 4];
TestNS:settings["d"] = {"a", "b", "c", "d"};
TestNS:settings["e"] = ["key" => 1];
/*
TestNS:settings["a"] = cur_settings["a"];
TestNS:settings["b"] = cur_settings["b"];
TestNS:settings["c"] = cur_settings["c"];
TestNS:settings["d"] = cur_settings["d"];
TestNS:settings["e"] = cur_settings["e"];
*/
myfilepath = Save Text File("$DOWNLOADS/myscript.jsl", As JSON Expr(TestNS:settings));
conf = Load Text File(myfilepath);
loaded_settings = Parse JSON(conf);
Luego, podría crear algunas funciones como save_settings, load_settings, ... si es necesario.
Re: Guardar un nuevo script para conservar las variables para más adelanteGracias tanto a Jarmo como a Jim, ambas soluciones funcionan. Inicialmente utilicé la solución de Jim, que podía conectarse directamente a lo que tenía inicialmente. Después de algunas revisiones, adapté la idea de Jarmo, que de hecho fue más sencilla de gestionar. Esto es con lo que terminé. Con esta configuración no necesitaba el espacio de nombres, pero aún así funcionaría con espacios de nombres.
names default to here (1);
//initialize variables
var1 = {"a", "b", "c"};
var2 = 100;
var3 = [1, 2, 3, 4];
//initialize variables used for functions
VarsToExport = {"var1", "var2", "var3"};
SettingsAA = Associative Array();
loaded_settingsAA = .;
SelfPath = Get Default Directory();
//expr to get each variable in the VarsToExport list and input the value into an AA, export as JSON
ExportVarsExpr = expr(
for each({varname}, VarsToExport,
//show(varname);
SettingsAA[varname] = eval(as name(varname));
//show(SettingsAA);
);
VarsSavePath = Pick File(
"Save a file containing current script settings",
SelfPath,
{"JMP Script Files|jsl", "All Files|*"},
1,
1,
"Layer_Settings.jsl"
);
Save Text File(VarsSavePath, As JSON Expr(settingsAA));
);
//expr open a jsl file, parse JSON into an AA and extract saved values
ImportVarsExpr = expr(
VarsImportPath = Pick File(
"Select jsl file that contains the saved parameters",
SelfPath,
{"JMP Script Files|jsl", "All Files|*"},
1,
0,
""
);
loaded_settingsAA = Parse JSON(Load Text File(VarsImportPath));
//for each element of AA, get the name of the element and set a variable with that name to the AA value
for each({varname}, loaded_settingsAA,
eval(parse(Evalinsert("\[ "^varname^"n = loaded_settingsAA << get value (varname) ]\")));
//show(varname);
//show(loaded_settingsAA << get value (varname));
);
);
//show original variables
Write("\!N", "Original:");
show(var1, var2, var2);
//export variables
eval(ExportVarsExpr);
//clear the variables
var1 = .;
var2 = .;
var3 = .;
Write("\!N", "\!N", "Variables cleared:");
show(var1, var2, var2);
//import variables
eval(ImportVarsExpr);
//show that the variables have been imported
Write("\!N", "\!N", "Post loading:");
show(var1, var2, var2);