之前已经在不同程度上提出了这类问题,但我觉得它没有以简洁的方式回答,所以我再次提出这个问题.
我想用Python运行一个脚本.让我们说是这样的:
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
s = f.read()
print s
Run Code Online (Sandbox Code Playgroud)
获取文件位置,读取它,然后打印其内容.没那么复杂.
好的,那我怎么在C#中运行呢?
这就是我现在拥有的:
private void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = cmd;
start.Arguments = args;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我通过code.py位置cmd和filename位置,因为args它不起作用.有人告诉我,我应该通过python.exe的cmd,然后code.py filename作为args …
有没有办法从C#调用Python代码,我假设使用IronPython?如果是这样,怎么样?
好吧,我有一个Python包.我需要将它编译为dll,然后以易于导入的方式分发它.怎么样?你可能会建议*.pyc.但我在某处读到任何*.pyc可以轻易反编译的内容!
更新:
遵循以下:
1)我写了一个python包
2)想要分发它
3)不要分发源
4)*.pyc可以解压缩>>源码可以提取!
5)dll是标准的
我有Visual Studio 2015,我的主要表单用C#编写,从那里我有不同的用Python编写的类(普通的Python而不是Iron Python).如何从C#代码中调用Python函数?
我知道有很多关于此的主题但是大多数都太旧了,有些解决方案太难或者涉及使用像C++这样的中间语言.
以下是我发现有用的一些链接,但没有提供我正在搜索的答案:
有一个简单的方法还是我还需要一个解决方法?如果我需要一个解决方法,那么最简单的是什么?
到目前为止,我有一个简单的类包装python引擎(IronPython)供我使用.虽然代码看起来很大,但它非常简单,所以我在这里复制它以便更清楚地解决我的问题.
这是代码:
public class PythonInstance
{
ScriptEngine engine;
ScriptScope scope;
ScriptSource source;
public PythonInstance()
{
engine = Python.CreateEngine();
scope = engine.CreateScope();
}
public void LoadCode(string code)
{
source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements);
source.Compile();
}
public void SetVariable(string key, dynamic variable)
{
scope.SetVariable(key, variable);
}
public void RunCode()
{
source.Execute(scope);
}
public void CallFunction(string function)
{
//?????? no idea what to call here
}
}
Run Code Online (Sandbox Code Playgroud)
所以,它工作得很好,但它只允许我一次执行所有python脚本......但我想做的是能够从pythos脚本中调用特定的函数.
所以,我的问题是:如何在加载的脚本中调用特定函数?
我试图找到一些信息或教程,但遗憾的是找不到任何东西.
c# ×4
python ×4
ironpython ×3
.net ×2
compilation ×1
dll ×1
dynamic ×1
module ×1
python.net ×1