-
Notifications
You must be signed in to change notification settings - Fork 122
/
RecordPythonScript.cpp
96 lines (76 loc) · 2.6 KB
/
RecordPythonScript.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "MantidAlgorithms/RecordPythonScript.h"
#include "MantidAPI/FileProperty.h"
#include <Poco/Thread.h>
#include <fstream>
using namespace Mantid::Kernel;
using namespace Mantid::API;
namespace Mantid {
namespace Algorithms {
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(RecordPythonScript)
//----------------------------------------------------------------------------------------------
/// Constructor
RecordPythonScript::RecordPythonScript()
: Algorithms::GeneratePythonScript(), API::AlgorithmObserver() {}
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
/** Initialize the algorithm's properties.
*/
void RecordPythonScript::init() {
declareProperty(Kernel::make_unique<API::FileProperty>(
"Filename", "", API::FileProperty::Save, ".py"),
"The file into which the Python script will be generated.");
}
//----------------------------------------------------------------------------------------------
/** Execute the algorithm.
*/
void RecordPythonScript::exec() {
observeStarting();
// Keep going until you get cancelled
while (true) {
try {
// Exit if the user presses cancel
interruption_point();
} catch (...) {
break;
}
progress(0.0, "Recording...");
// Sleep for 50 msec
Poco::Thread::sleep(50);
}
// save the script to a file
const std::string filename = getPropertyValue("Filename");
std::ofstream file(filename.c_str(), std::ofstream::trunc);
if (file.is_open()) {
file << m_generatedScript;
file.flush();
file.close();
} else {
throw Exception::FileError("Unable to create file: ", filename);
}
stopObservingManager();
}
/** Handler of the start notifications. Adds an algorithm call to the script.
* @param alg :: Shared pointer to the starting algorithm.
*/
void RecordPythonScript::startingHandle(API::IAlgorithm_sptr alg) {
auto props = alg->getProperties();
std::string algString;
for (auto &prop : props) {
std::string opener = "='";
if ((*prop).value().find('\\') != std::string::npos) {
opener = "=r'";
}
std::string paramString = (*prop).name() + opener + (*prop).value() + "'";
// Miss out parameters that are empty.
if (paramString.length() != 0) {
if (algString.length() != 0) {
algString += ",";
}
algString += paramString;
}
}
m_generatedScript += alg->name() + "(" + algString + ")\n";
}
} // namespace Algorithms
} // namespace Mantid