PYTHON:nosetests用多个模块/文件导入文件路径(PYTHON: nosetests import file path with multiple modules/files)
我目前正在通过LearnPythonTheHardWay进行工作,并已经完成了详细的Nosetests 练习48 。 只要所有的代码都在一个python.py文件中,我就可以执行单元测试。 但是,如果我包含其他文件作为程序的一部分,即使用导入 ,然后尝试nosetest这样的项目,我收到一个错误,如下所示:
================================================== ====================
错误:失败:ImportError(没有名为'temp'的模块)
回溯(最近一次通话最后):
文件“/usr/local/lib/python3.4/dist-packages/nose/failure.py”,第39行,在runTest中
raise self.exc_val.with_traceback(self.tb)
文件“/usr/local/lib/python3.4/dist-packages/nose/loader.py”,第414行,在loadTestsFromName ## ##
addr.filename,addr.module)
在importFromPath中的文件“/usr/local/lib/python3.4/dist-packages/nose/importer.py”,第47行
return self.importFromDir(dir_path,fqname)
在importFromDir中的文件“/usr/local/lib/python3.4/dist-packages/nose/importer.py”,第94行
mod = load_module(part_fqname,fh,filename,desc)
在load_module中的文件“/usr/lib/python3.4/imp.py”,第235行
返回load_source(名称,文件名,文件)
文件“/usr/lib/python3.4/imp.py”,第171行,在load_source中
module = methods.load()
文件“”,第1220行,载入
文件“”,第1200行,在_load_unlocked
文件“”,行1129,在_exec
文件“”,行1471,在exec_module中
文件“”,行321,在_call_with_frames_removed
文件“/home/user/LEARNPYTHONTHEHARDWAY/ex48/tests/scanner_tests.py”,第6行,在
来自ex48.scanner导入词典
文件“/home/user/LEARNPYTHONTHEHARDWAY/ex48/ex48/scanner.py”,第6行,在
进口温度
ImportError:没有名为'temp'的模块
冉1测试在0.028s
失败(错误= 1)
我的项目目录结构如下:
ex48/ ex48/ scanner.py temp.py __pycache__/ tests/ __init__.py scanner_tests.py
我的目录的屏幕截图:
文件本身的屏幕截图::
from nose.tools import * from ex48.scanner import lexicon from ex48 import temp def test_directions(): assert_equal(lexicon.scan("north"),[('direction','north')]) result = lexicon.scan("north south east") assert_equal(result, [('direction', 'north'), ('direction', 'south'), ('direction', 'east')])
我的scanner.py文件如下所示:
import temp class lexicon: def scan(val): if(val == "north"): return [('direction', 'north')] else: return [('direction', 'north'), ('direction', 'south'), ('direction', 'east')] runner = temp.temp("hello")
最后我的temp.py文件如下:
class temp(object): def __init__(self,name): self.name = name def run(self): print "Your name is; %s" % self.name runner.run()
我的问题是如何克服ImportError:No Module named'temp ',因为它看起来好像我已经在scanner.py文件和scanner_tests.py文件中导入了temp.py文件,但鼻子似乎无法运行时导入它。 当它只是单个scanner.py文件时, Nosetests可以正常工作,但在导入时无法正常工作。 是否有一个特殊的语法导入鼻子的单元测试? 在命令行运行并正确导入时,该脚本也可以正常工作。
*注意:我正在关闭在线服务器的有限帐户运行python,因此某些管理员权限不可用。
**注意下面是完全不同的另一个项目的截图,具有完全相同的错误:
Game.py:
Otherpy.py - 导入的文件:
鼻子测试脚本文件:
最后nosetests importerror:
I'm currently working through LearnPythonTheHardWay and have reached Exercise 48 which details Nosetests. I am able to perform a unit testing as long as all of the code is in a single python.py file. However if I include other files as part of a program, i.e. use import and then attempt to nosetest such a project I am getting an error, as follows:
======================================================================
ERROR: Failure: ImportError (No module named 'temp')
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/usr/local/lib/python3.4/dist-packages/nose/loader.py", line 414, in loadTestsFromName ## ##
addr.filename, addr.module)
File "/usr/local/lib/python3.4/dist-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/usr/local/lib/python3.4/dist-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/usr/lib/python3.4/imp.py", line 235, in load_module
return load_source(name, filename, file)
File "/usr/lib/python3.4/imp.py", line 171, in load_source
module = methods.load()
File "", line 1220, in load
File "", line 1200, in _load_unlocked
File "", line 1129, in _exec
File "", line 1471, in exec_module
File "", line 321, in _call_with_frames_removed
File "/home/user/LEARNPYTHONTHEHARDWAY/ex48/tests/scanner_tests.py", line 6, in
from ex48.scanner import lexicon
File "/home/user/LEARNPYTHONTHEHARDWAY/ex48/ex48/scanner.py", line 6, in
import temp
ImportError: No module named 'temp'
Ran 1 test in 0.028s
FAILED (errors=1)
The structure of my project directories are as follows:
ex48/ ex48/ scanner.py temp.py __pycache__/ tests/ __init__.py scanner_tests.py
Screenshot of my directory::
Screen shot of files themselves::
My scanner_tests.py file is as follows:
from nose.tools import * from ex48.scanner import lexicon from ex48 import temp def test_directions(): assert_equal(lexicon.scan("north"),[('direction','north')]) result = lexicon.scan("north south east") assert_equal(result, [('direction', 'north'), ('direction', 'south'), ('direction', 'east')])
My scanner.py file is as follows:
import temp class lexicon: def scan(val): if(val == "north"): return [('direction', 'north')] else: return [('direction', 'north'), ('direction', 'south'), ('direction', 'east')] runner = temp.temp("hello")
And finally my temp.py file is as follows:
class temp(object): def __init__(self,name): self.name = name def run(self): print "Your name is; %s" % self.name runner.run()
My question is how to overcome the ImportError: No Module named 'temp' because it seems as if I have imported the temp.py file in both the scanner.py file and the scanner_tests.py file but nose does not seem to be able to import it when it runs. Nosetests works fine when its just the single scanner.py file but not when importing. Is there a special syntax for importing into a unit test for nose? The script also works fine when run and imports properly at the command line.
*Note: I'm running python off a limited account off an online server so some admin privileges are not available.
**Note below are entirely different screenshots from another project with the exact same error:
Game.py:
Otherpy.py - the imported file:
the Nose test script file:
And finally the nosetests importerror:
原文:https://stackoverflow.com/questions/36318440
最满意答案
对,经过很多实验后,我设法弄清楚了这一点。
事实证明,excel分别为正常单元格和“Gray125”图案填充保留样式0和1。 大部分上述代码都可以被删除,因为我们只需要一个
CellFormat
。工作代码:
Console.WriteLine("Creating document"); using (var spreadsheet = SpreadsheetDocument.Create("output.xlsx", SpreadsheetDocumentType.Workbook)) { Console.WriteLine("Creating workbook"); spreadsheet.AddWorkbookPart(); spreadsheet.WorkbookPart.Workbook = new Workbook(); Console.WriteLine("Creating worksheet"); var wsPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>(); wsPart.Worksheet = new Worksheet(); var stylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>(); stylesPart.Stylesheet = new Stylesheet(); Console.WriteLine("Creating styles"); // blank font list stylesPart.Stylesheet.Fonts = new Fonts(); stylesPart.Stylesheet.Fonts.Count = 1; stylesPart.Stylesheet.Fonts.AppendChild(new Font()); // create fills stylesPart.Stylesheet.Fills = new Fills(); // create a solid red fill var solidRed = new PatternFill() { PatternType = PatternValues.Solid }; solidRed.ForegroundColor = new ForegroundColor { Rgb = HexBinaryValue.FromString("FFFF0000") }; // red fill solidRed.BackgroundColor = new BackgroundColor { Indexed = 64 }; stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = new PatternFill { PatternType = PatternValues.None } }); // required, reserved by Excel stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = new PatternFill { PatternType = PatternValues.Gray125 } }); // required, reserved by Excel stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = solidRed }); stylesPart.Stylesheet.Fills.Count = 3; // blank border list stylesPart.Stylesheet.Borders = new Borders(); stylesPart.Stylesheet.Borders.Count = 1; stylesPart.Stylesheet.Borders.AppendChild(new Border()); // blank cell format list stylesPart.Stylesheet.CellStyleFormats = new CellStyleFormats(); stylesPart.Stylesheet.CellStyleFormats.Count = 1; stylesPart.Stylesheet.CellStyleFormats.AppendChild(new CellFormat()); // cell format list stylesPart.Stylesheet.CellFormats = new CellFormats(); // empty one for index 0, seems to be required stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat()); // cell format references style format 0, font 0, border 0, fill 2 and applies the fill stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat { FormatId = 0, FontId = 0, BorderId = 0, FillId = 2, ApplyFill = true }).AppendChild(new Alignment { Horizontal = HorizontalAlignmentValues.Center }); stylesPart.Stylesheet.CellFormats.Count = 2; stylesPart.Stylesheet.Save(); Console.WriteLine("Creating sheet data"); var sheetData = wsPart.Worksheet.AppendChild(new SheetData()); Console.WriteLine("Adding rows / cells..."); var row = sheetData.AppendChild(new Row()); row.AppendChild(new Cell() { CellValue = new CellValue("This"), DataType = CellValues.String }); row.AppendChild(new Cell() { CellValue = new CellValue("is"), DataType = CellValues.String }); row.AppendChild(new Cell() { CellValue = new CellValue("a"), DataType = CellValues.String }); row.AppendChild(new Cell() { CellValue = new CellValue("test."), DataType = CellValues.String }); sheetData.AppendChild(new Row()); row = sheetData.AppendChild(new Row()); row.AppendChild(new Cell() { CellValue = new CellValue("Value:"), DataType = CellValues.String }); row.AppendChild(new Cell() { CellValue = new CellValue("123"), DataType = CellValues.Number }); row.AppendChild(new Cell() { CellValue = new CellValue("Formula:"), DataType = CellValues.String }); // style index = 1, i.e. point at our fill format row.AppendChild(new Cell() { CellFormula = new CellFormula("B3"), DataType = CellValues.Number, StyleIndex = 1 }); Console.WriteLine("Saving worksheet"); wsPart.Worksheet.Save(); Console.WriteLine("Creating sheet list"); var sheets = spreadsheet.WorkbookPart.Workbook.AppendChild(new Sheets()); sheets.AppendChild(new Sheet() { Id = spreadsheet.WorkbookPart.GetIdOfPart(wsPart), SheetId = 1, Name = "Test" }); Console.WriteLine("Saving workbook"); spreadsheet.WorkbookPart.Workbook.Save(); Console.WriteLine("Done."); }
一些忠告:
如果您想避免这种疯狂,请使用ClosedXML。
如果您正在从事这类工作,我无法推荐ClosedXML 。 OpenXML API和格式非常单调乏味,无法处理各种无证件情况。 ClosedXML为你做了很多工作。 他们也很擅长迅速修复错误。
Right, I managed to figure this out, after a lot of experimentation.
It turns out that excel reserves styles 0 and 1 for normal cells and "Gray125" pattern fill respectively. Most of the above code can be removed, as we only need a
CellFormat
really.Working code:
Console.WriteLine("Creating document"); using (var spreadsheet = SpreadsheetDocument.Create("output.xlsx", SpreadsheetDocumentType.Workbook)) { Console.WriteLine("Creating workbook"); spreadsheet.AddWorkbookPart(); spreadsheet.WorkbookPart.Workbook = new Workbook(); Console.WriteLine("Creating worksheet"); var wsPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>(); wsPart.Worksheet = new Worksheet(); var stylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>(); stylesPart.Stylesheet = new Stylesheet(); Console.WriteLine("Creating styles"); // blank font list stylesPart.Stylesheet.Fonts = new Fonts(); stylesPart.Stylesheet.Fonts.Count = 1; stylesPart.Stylesheet.Fonts.AppendChild(new Font()); // create fills stylesPart.Stylesheet.Fills = new Fills(); // create a solid red fill var solidRed = new PatternFill() { PatternType = PatternValues.Solid }; solidRed.ForegroundColor = new ForegroundColor { Rgb = HexBinaryValue.FromString("FFFF0000") }; // red fill solidRed.BackgroundColor = new BackgroundColor { Indexed = 64 }; stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = new PatternFill { PatternType = PatternValues.None } }); // required, reserved by Excel stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = new PatternFill { PatternType = PatternValues.Gray125 } }); // required, reserved by Excel stylesPart.Stylesheet.Fills.AppendChild(new Fill { PatternFill = solidRed }); stylesPart.Stylesheet.Fills.Count = 3; // blank border list stylesPart.Stylesheet.Borders = new Borders(); stylesPart.Stylesheet.Borders.Count = 1; stylesPart.Stylesheet.Borders.AppendChild(new Border()); // blank cell format list stylesPart.Stylesheet.CellStyleFormats = new CellStyleFormats(); stylesPart.Stylesheet.CellStyleFormats.Count = 1; stylesPart.Stylesheet.CellStyleFormats.AppendChild(new CellFormat()); // cell format list stylesPart.Stylesheet.CellFormats = new CellFormats(); // empty one for index 0, seems to be required stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat()); // cell format references style format 0, font 0, border 0, fill 2 and applies the fill stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat { FormatId = 0, FontId = 0, BorderId = 0, FillId = 2, ApplyFill = true }).AppendChild(new Alignment { Horizontal = HorizontalAlignmentValues.Center }); stylesPart.Stylesheet.CellFormats.Count = 2; stylesPart.Stylesheet.Save(); Console.WriteLine("Creating sheet data"); var sheetData = wsPart.Worksheet.AppendChild(new SheetData()); Console.WriteLine("Adding rows / cells..."); var row = sheetData.AppendChild(new Row()); row.AppendChild(new Cell() { CellValue = new CellValue("This"), DataType = CellValues.String }); row.AppendChild(new Cell() { CellValue = new CellValue("is"), DataType = CellValues.String }); row.AppendChild(new Cell() { CellValue = new CellValue("a"), DataType = CellValues.String }); row.AppendChild(new Cell() { CellValue = new CellValue("test."), DataType = CellValues.String }); sheetData.AppendChild(new Row()); row = sheetData.AppendChild(new Row()); row.AppendChild(new Cell() { CellValue = new CellValue("Value:"), DataType = CellValues.String }); row.AppendChild(new Cell() { CellValue = new CellValue("123"), DataType = CellValues.Number }); row.AppendChild(new Cell() { CellValue = new CellValue("Formula:"), DataType = CellValues.String }); // style index = 1, i.e. point at our fill format row.AppendChild(new Cell() { CellFormula = new CellFormula("B3"), DataType = CellValues.Number, StyleIndex = 1 }); Console.WriteLine("Saving worksheet"); wsPart.Worksheet.Save(); Console.WriteLine("Creating sheet list"); var sheets = spreadsheet.WorkbookPart.Workbook.AppendChild(new Sheets()); sheets.AppendChild(new Sheet() { Id = spreadsheet.WorkbookPart.GetIdOfPart(wsPart), SheetId = 1, Name = "Test" }); Console.WriteLine("Saving workbook"); spreadsheet.WorkbookPart.Workbook.Save(); Console.WriteLine("Done."); }
Some advice:
Use ClosedXML if you want to avoid this insanity.
I cannot recommend ClosedXML highly enough if you're doing this kind of work. The OpenXML API and format is horribly tedious to work with on its own, with all sorts of undocumented cases. ClosedXML does so much of the leg work for you. They're also really great at getting bugs fixed quickly.
相关问答
更多-
对,经过很多实验后,我设法弄清楚了这一点。 事实证明,excel分别为正常单元格和“Gray125”图案填充保留样式0和1。 大部分上述代码都可以被删除,因为我们只需要一个CellFormat 。 工作代码: Console.WriteLine("Creating document"); using (var spreadsheet = SpreadsheetDocument.Create("output.xlsx", SpreadsheetDocumentType.Workbook)) { Con ...
-
您可以使用Row实例的Parent属性导航到该行所属的Worksheet 。 关于Row类的以下MSDN文章明确指出Row实例的唯一父元素是该行所属的SheetData对象。 SheetData对象唯一可能的Parent对象是Worksheet实例(有关更多信息,请参阅SheetData类上的以下MSDN文章 )。 例: 以下示例显示如何导航到给定Row实例所属的Worksheet 。 为方便起见,我创建了一个扩展方法: public static class RowExtensionMethods { ...
-
Open XML SDK不会刷新公式的计算结果。 只有Excel可以这样做(或其他电子表格软件)。 因此,即使您将ForceFullCalculation和FullCalculationOnLoad设置为true,您也只会告诉Excel强制进行完整计算,并在加载电子表格文件时执行此操作。 这就是为什么你总是得到“旧”的价值。 因为没有什么“新”价值可言。 为了测试这个,你可以设置CellValue(Cell类的)为CellFormula完整的“3.14159”。 即使您专门将单元格值设置为“3.14159” ...
-
有点晚了,但我面临着同样的任务,我创建了一个Excel表格,并手动添加了一个图表标题的图表,然后打开xml以了解需要哪些标签。 过了一段时间,我得到了它的工作。 将所有内容都移动到如下的小函数中: 所以你可以提供你的图表对象和你想要的标题给下面的函数,它会添加图表标题。 注意:我使用Microsoft Office的Open XML SDK 2.0 private void AddChartTitle(DocumentFormat.OpenXml.Drawing.Charts.Chart chart,str ...
-
尝试这个: using (SpreadsheetDocument ssd = SpreadsheetDocument.Open(Server.MapPath(@"\ExcelPackageTemplate.xlsx"), true)) { WorkbookPart wbPart = ssd.WorkbookPart; WorksheetPart worksheetPart = wbPart.WorksheetParts.First(); SheetData sheetdata = ...
-
答案是否定的。 The answer is NO.
-
如果要删除所有公式,那么需要一个空的calcChain.xml是什么? 你试过删除吗? 这对我有用: public static void ReplaceFormulasWithValue() { try { CalculationChainPart calculationChainPart = _spreadSheet.WorkbookPart.CalculationChainPart; CalculationChain calculationChain = ...
-
OpenXML linq查询(OpenXML linq query)[2024-01-04]
OpenXML标准没有为没有数据的单元定义占位符。 换句话说,它在XML中的底层存储是稀疏的。 您可以通过以下两种方式之一来解决此问题: 创建所有“可用”或“可能”单元的列表(可能通过使用CROSS JOIN类型的操作),然后“左”加入到row.Descendants()集合中,以查看单元格引用是否具有值 利用第三方工具(如ClosedXML或EPPlus)作为Excel数据的包装并查询其界面,这些界面更适合开发人员。 The OpenXML standard does not define p ... | -
在下面的代码块中,sst.ChildElements [7] .InnerText获取第一行第7列的内容,但每次循环它的内容都来自同一个CELL! 这是因为您始终读取SharedStringsTable (您的sst变量)中的元素7的值,而不是来自Row (您的row变量)中元素7的值。 共享字符串表是OpenXML中使用的一种机制,用于防止重复数据出现在单元格中(以减小文件大小)。 而不是直接包含字符串值的单元格,而是可以包含一个整数,该整数是共享字符串表中的索引。 这样,如果一个字符串在一个Excel文 ...
-
在excel中,所有与样式相关的信息都存储在style.xml文件中。 因此,包装信息应该存储在style.xml中,样式Id应该在
作为另一个属性's'(表示样式)。 让我说明这是什么意思.. 我确实有一些excel有一些文本,并且单元格确实被包裹了。 如果我看到它的sheet.xml数据,它将在 标记中有s="1"属性值项。 所以,如果我打开style.xml并查看单元格样式信息,我将获得 标签和 子标签,其中我得到一个带有wrapT ...