File: system.cpp

package info (click to toggle)
wsclean 2.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 2,196 kB
  • sloc: cpp: 34,504; ansic: 234; python: 174; makefile: 10
file content (56 lines) | stat: -rw-r--r-- 1,848 bytes parent folder | download
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
#include "system.h"

#include "wsclean/logger.h"

#include <boost/filesystem.hpp>

#include <cstdlib>
#include <fstream>
#include <sstream>
#include <random>

std::string System::FindPythonFilePath(const std::string& filename)
{
	if(boost::filesystem::exists(filename))
		return filename;
	Logger::Debug << "Searching " << filename << "... ";
	Logger::Debug.Flush();
	std::random_device rndDev;
  std::mt19937 gen(rndDev());
	std::stringstream filenameStr;
	filenameStr << "/tmp/ao-python-path-list" << gen() << ".tmp";
	boost::filesystem::path tempPath = filenameStr.str(); //boost::filesystem::unique_path();
	const std::string tempFilename = tempPath.string();  // optional
	std::string command =
		std::string("echo \"import sys\nfor a in sys.path:\n  print a\"|python>") +
		tempFilename;
	int status = system(command.c_str());
	if(status != 0)
	  throw std::runtime_error("system() returned non-zero error code: might be out of memory, or python might not be working properly");
	std::ifstream searchPathsFile(tempFilename.c_str());
	if(!searchPathsFile.good())
	  throw std::runtime_error(("Error in findPythonFilePath: system call did not create expected temporary file " + tempFilename).c_str());
	while(searchPathsFile.good())
	{
		std::string prefixPath;
		std::getline(searchPathsFile, prefixPath);
		boost::filesystem::path searchPath(prefixPath);
		searchPath /= filename;
		
		bool pathExists = false;
		try {
			pathExists = boost::filesystem::exists(searchPath);
		} catch(...) { }
		if(pathExists)
		{
			const std::string result = searchPath.string();
			Logger::Debug << result << '\n';
			searchPathsFile.close();
			boost::filesystem::remove(tempPath);
			return result;
		}
	}
	searchPathsFile.close();
	boost::filesystem::remove(tempPath);
	throw std::runtime_error(std::string("Could not find Python file ") + filename);
}