关于IronPython:使用pyc.py编译的EXE无法导入模块“OS”和python编译的exe无法在其他电脑运行的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于asp.net–在C#
关于IronPython:使用pyc.py编译的EXE无法导入模块“ OS”和python编译的exe无法在其他电脑运行的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于asp.net – 在C#中从IronPython调用时引用Python“导入”程序集、c# – IronPython,导入模块、C#使用IronPython库调用Python脚本、IronPython无法导入模块操作系统等相关知识的信息别忘了在本站进行查找喔。
本文目录一览:- IronPython:使用pyc.py编译的EXE无法导入模块“ OS”(python编译的exe无法在其他电脑运行)
- asp.net – 在C#中从IronPython调用时引用Python“导入”程序集
- c# – IronPython,导入模块
- C#使用IronPython库调用Python脚本
- IronPython无法导入模块操作系统
IronPython:使用pyc.py编译的EXE无法导入模块“ OS”(python编译的exe无法在其他电脑运行)
我有一个简单的IronPython脚本:
# Foo.pyimport osdef main(): print( "Hello" )if "__main__" == __name__: main()
它运行良好,并打印 你好 ,如果我的IronPython的运行:
ipy Foo.py
按照 IronPython中 给出的说明 -如何编译exe ,我使用以下命令将该IronPython脚本编译为EXE:
ipy pyc.py /main:Foo.py /target:exe
执行Foo.exe会出现此错误:
Unhandled Exception: IronPython.Runtime.Exceptions.ImportException: No module named os at Microsoft.Scripting.Runtime.LightExceptions.CheckAndThrow(Object value) at DLRCachedCode.__main__$1(CodeContext $globalContext, FunctionCode $functionCode) at IronPython.Compiler.OnDiskScriptCode.Run() at IronPython.Compiler.OnDiskScriptCode.Run(Scope scope) at IronPython.Runtime.PythonContext.InitializeModule(String fileName, ModuleContext moduleContext, ScriptCode scriptCode, ModuleOptions options)
为什么找不到模块“ os”?我该如何解决这个问题,以便获得可以运行的EXE?
答案1
小编典典构建一个可以分发的Ironpython EXE有点棘手-尤其是在使用标准库的元素时。我的典型解决方案如下:
我将我需要的所有stdlib模块复制到一个文件夹中(通常是出于完整性的考虑),并使用此脚本来构建我的exe。在此示例中,我有两个文件
FredMain.py 和 FredSOAP.py ,它们被编译成一个名为 Fred_Download_Tool 的EXE。
import syssys.path.append(r''C:\Program Files\IronPython 2.7\Lib'')sys.path.append(r''C:\Program Files\IronPython 2.7'')import clrclr.AddReference(''IronPython'')clr.AddReference(''IronPython.Modules'')clr.AddReference(''Microsoft.Scripting.Metadata'')clr.AddReference(''Microsoft.Scripting'')clr.AddReference(''Microsoft.Dynamic'')clr.AddReference(''mscorlib'')clr.AddReference(''System'')clr.AddReference(''System.Data'')## adapted from os-path-walk-example-3.pyimport os, globimport fnmatchimport pycdef doscopy(filename1): print filename1 os.system ("copy %s .\\bin\Debug\%s" % (filename1, filename1))class GlobDirectoryWalker: # a forward iterator that traverses a directory tree def __init__(self, directory, pattern="*"): self.stack = [directory] self.pattern = pattern self.files = [] self.index = 0 def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # got a filename fullname = os.path.join(self.directory, file) if os.path.isdir(fullname) and not os.path.islink(fullname) and fullname[-4:]<>''.svn'': self.stack.append(fullname) if fnmatch.fnmatch(file, self.pattern): return fullname#Build StdLib.DLLgb = glob.glob(r".\Lib\*.py")gb.append("/out:StdLib")#print ["/target:dll",]+gbpyc.Main(["/target:dll"]+gb)#Build EXEgb=["/main:FredMain.py","FredSOAP.py","/target:exe","/out:Fred_Download_Tool"]pyc.Main(gb)#CopyFiles to Release Directorydoscopy("StdLib.dll")doscopy("Fred_Download_Tool.exe")doscopy("Fred_Download_.dll")#Copy DLLs to Release Directoryfl = ["IronPython.dll","IronPython.Modules.dll","Microsoft.Dynamic.dll","Microsoft.Scripting.Debugging.dll","Microsoft.Scripting.dll","Microsoft.Scripting.ExtensionAttribute.dll","Microsoft.Scripting.Core.dll"]for f in fl:doscopy(f)
准备编译时,在脚本中添加以下内容。这允许程序使用我DLL中的标准模块,而不是Python
Install。如果要分发给未安装Python的人,这是必需的。只需确保在创建安装程序时包括必要的DLL。
#References to created DLL of python modulesclr.AddReference(''StdLib'')
asp.net – 在C#中从IronPython调用时引用Python“导入”程序集
var ipy = IronPython.Hosting.Python.CreateRuntime(); dynamic test = ipy.UseFile(Server.MapPath(@"~\python\test.py")); test.DoWork();
我使用的IronPython版本是2.7。
我需要调用的第三方python文件具有以下导入指令:
import sys from array import * from subprocess import *
我收到错误“No module named subprocess”。我已经从IronPython安装Lib目录中复制了subprocess.py文件,但我认为我需要在C#代码中链接到它
谢谢。
编辑:
我找到了解决方案:
ScriptEngine scriptEngine = Python.CreateEngine(); var sp = scriptEngine.GetSearchPaths(); sp.Add(Server.MapPath(@"~\python\lib")); scriptEngine.SetSearchPaths(sp); var scope = scriptEngine.Runtime.ExecuteFile(Server.MapPath(@"~\python\test.py"));
如果任何人有任何意见/改进,请随时详细说明,因为我在所有这些Python / IronPython恶意软件的新的领域。
解决方法
dynamic sys = scriptEngine.ImportModule("sys"); sys.path.append(somePath);
c# – IronPython,导入模块
Build Python scripts and call methods from C#
我在pyScope = pyEngine.ImportModule(“MyClass”)中得到一个例外;
no module named MyClass
我相信这是一个错误,因为有时使用Pyc.py进行重新编译会生成一个dll ImportModule识别,但有时它不会.
结论:如下面通过digEmAll所述,以这种方式使用Pyc.py编译模块会产生随机结果.而是手动调用clr.CompileModules.
解决方法
我知道了.
模块名称是原始.py模块的(区分大小写)名称,而不是已编译的dll.
我的意思是,如果您的原始模块名称是myClass.py,那么您在MyClass.dll中编译它,您必须ImportModule(“myClass”)而不是ImportModule(“MyClass”)
编辑:
前面的代码引用了以下编译方法:
import clr clr.CompileModules("CompiledScript.dll","script.py")
相反,使用pyc.py,生成的dll包含一个名为__main__的模块,而不是.py文件名.
那很奇怪……
IIRC,在python中,一个模块调用自己__main__如果它是独立运行的(即没有被另一个调用),但我仍然没有掌握连接……
C#使用IronPython库调用Python脚本
IronPython是一种在 .NET及 Mono上的 Python实现,由微软的 Jim Hugunin所发起,是一个开源的项目,基于微软的 DLR引擎。
IronPython的主页: IronPython.net /
github站点:
IronLanguages/ironpython3: Implementation of Python 3.x for .NET Framework that is built on top of the Dynamic Language Runtime. (github.com)
IronLanguages/ironpython2: Implementation of the Python programming language for .NET Framework; built on top of the Dynamic Language Runtime (DLR). (github.com)
方式一:适用于python脚本中不包含第三方模块的情况
1、执行语句
借由IronPython,就可以利用.NET执行存储在Python脚本中的代码段。下面通过简单的示例说明如何应用C#调用Python脚本。
1、在VS中新建窗体项目:IronPythonDemo
2、VS的菜单中打开“Nuget程序包管理器”
3、搜索IronPython程序包并安装
安装后自动引用如下的DLL
4、在exe程序所在文件夹下创建Python脚本。Python示例脚本实现求两个数的四则运算:
num1=arg1 num2=arg2 op=arg3 if op==1: result=num1+num2 elif op==2: result=num1-num2 elif op==3: result=num1*num2 else: result=num1*1.0/num2
设置IronPythonDemo.py文件属性为“复制到输出目录”
5、修改工程的配置文件App.config如下:
其中microsoft.scripting节点中设置了IronPython语言引擎的几个属性。
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="microsoft.scripting" type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting"/> </configSections> <microsoft.scripting> <languages> <language names="IronPython;Python;py" extensions=".py" displayName="Python" type="IronPython.Runtime.PythonContext, IronPython"/> </languages> </microsoft.scripting> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration>
6、 绘制窗体如下:
7、编写计算的函数:
ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration(); ScriptEngine pyEngine = scriptRuntime.GetEngine("python"); ScriptSource source = pyEngine.CreateScriptSourceFromFile("IronPythonDemo.py");//设置脚本文件 ScriptScope scope = pyEngine.CreateScope(); try { //设置参数 scope.SetVariable("arg1", Convert.ToInt32(txtNum1.Text)); scope.SetVariable("arg2", Convert.ToInt32(txtNum2.Text)); scope.SetVariable("arg3", operation.SelectedIndex + 1); } catch (Exception) { MessageBox.Show("输入有误。"); } source.Execute(scope); labelResult.Text = scope.GetVariable("result").ToString(); }
8、编译运行可得计算结果(此处未做输入的检查)
2、执行函数
IronPythonDemo2.py
def main(arr): try: arr = set(arr) arr = sorted(arr) arr = arr[0:] return str(arr) except Exception as err: return str(err)
c#代码
ScriptEngine pyEngine = IronPython.Hosting.Python.CreateEngine();//创建Python解释器对象 dynamic py = pyEngine.ExecuteFile(@"IronPythonDemo2.py");//读取脚本文件 int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 }; string reStr = py.main(array);//调用脚本文件中对应的函数 MessageBox.Show(reStr); //或者 ScriptRuntime pyRuntime = IronPython.Hosting.Python.CreateRuntime(); //创建一下运行环境 dynamic obj = pyRuntime.UseFile("IronPythonDemo2.py"); //调用一个Python文件 int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 }; string reStr = obj.main(array);//调用脚本文件中对应的函数 MessageBox.Show(reStr);
方式二:适用于python脚本中包含第三方模块的情况
C#代码
using System; using System.Collections; using System.Diagnostics; namespace Test { class Program { static void Main(string[] args) { Process p = new Process(); string path = "reset_ipc.py";//待处理python文件的路径,本例中放在debug文件夹下 string sArguments = path; ArrayList arrayList = new ArrayList(); arrayList.Add("com4"); arrayList.Add(57600); arrayList.Add("password"); foreach (var param in arrayList)//添加参数 { sArguments += " " + sigstr; } p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安装路径 p.StartInfo.Arguments = sArguments;//python命令的参数 p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.Start();//启动进程 Console.WriteLine("执行完毕!"); Console.ReadKey(); } } }
python脚本
# -*- coding: UTF-8 -*- import serial import time def resetIPC(com, baudrate, password, timeout=0.5): ser=serial.Serial(com, baudrate, timeout=timeout) flag=True try: ser.close() ser.open() ser.write("\n".encode("utf-8")) time.sleep(1) ser.write("root\n".encode("utf-8")) time.sleep(1) passwordStr="%s\n" % password ser.write(passwordStr.encode("utf-8")) time.sleep(1) ser.write("killall -9 xxx\n".encode("utf-8")) time.sleep(1) ser.write("rm /etc/xxx/xxx_user.*\n".encode("utf-8")) time.sleep(1) ser.write("reboot\n".encode("utf-8")) time.sleep(1) except Exception: flag=False finally: ser.close() return flag resetIPC(sys.argv[1], sys.argv[2], sys.argv[3])
上面的python脚本实现的是重启IPC设备,测试功能成功。
调用包含第三方模块的python脚本时,尝试过使用path.append()方式,调试有各种问题,最终放弃了,没有研究。
到此这篇关于C#使用IronPython库调用Python脚本的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。
- IronPython连接MySQL的方法步骤
- 在ironpython中利用装饰器执行SQL操作的例子
- 使用IronPython把Python脚本集成到.NET程序中的教程
- 推荐下python/ironpython:从入门到精通
IronPython无法导入模块操作系统
因此,我有一个基本的ZIPPED IronPython(2.6或2.6.1),可以将其解压缩,启动ipy.exe,键入“ import
os”并按Enter。发生以下输出:
Traceback (most recent call last):
File "<stdin>",line 1,in <module>
ImportError: No module named os
即使我先导入clr,它也不起作用。该怎么办?
我已经用谷歌搜索了这个问题,但是没有相关的答案。最接近的想法是这样(不起作用):
import clr
clr.AddReference("IronPython")
clr.AddReference("IronPython.Modules")
import os
今天关于IronPython:使用pyc.py编译的EXE无法导入模块“ OS”和python编译的exe无法在其他电脑运行的讲解已经结束,谢谢您的阅读,如果想了解更多关于asp.net – 在C#中从IronPython调用时引用Python“导入”程序集、c# – IronPython,导入模块、C#使用IronPython库调用Python脚本、IronPython无法导入模块操作系统的相关知识,请在本站搜索。
本文标签: