使用Python for .NET的Python提早终止

时间:2019-06-24 21:27:40

标签: c# python clr python.net

我正在尝试使用Python自动化应用程序。虽然我知道应用程序GUI在表面上是如何工作的,但是它是用C#编写的,而且我在遵循源代码方面几乎没有成功(虽然能流畅地使用Python,但我对C#不太熟悉)。我也不知道是谁创建了该应用程序-如果可能的话,这将是我的主要帮助来源。

我最初尝试使用使应用程序自动化的方法是将Python用于.NET(http://pythonnet.github.io/),这使我可以将C#代码导入Python并访问类及其方法。到目前为止,这已经很成功了,我已经能够调用该应用程序并运行它。但是,在完成该过程之后,Python终止并且在调用C#代码之后没有Python代码执行。

从本质上讲,C#应用程序采用两个输入文件的路径,在两个输入文件之间执行一些操作,结果输出一个文件。这是我的python脚本:

import sys, clr

# add location of .dll to path
sys.path.append(r'path\to\dll\net472')

# name of the dll
clr.AddReference("MatchingDLL")

# from the DLL, import the MainProgram (which contains a Main() method which appears to 'run' everything)
from MatchingDLL import MainProgram

def worker():
    # create an instance of MainProgram, then set attributes which would normally be input in the GUI
    mp = MainProgram()
    mp.main_input_source = 'test_source.txt'
    mp.main_input_lookup = 'test_lookup.txt'
    mp.output_folder = r'\output\dir'
    mp.output_name = 'test_output.txt'
    # call the Main() method to run the application
    mp.Main()

if __name__ == '__main__':
    print('start')
    worker()
    # worker() successfully runs and produces a proper output file, but Python terminates before the print statement below is reached
    print('end')

该应用程序被调用并成功运行,产生了一个不错的输出文件。但是,Python在C#的Main()方法结束时终止。

这是MainProgram的C#代码:

public class MainProgram
    {
        public string main_input_source;
        public string main_input_lookup;
        public string output_folder;
        public string output_name;
        [STAThread]
        public void Main()
        {
            Application.EnableVisualStyles();
            /*Application.SetCompatibleTextRenderingDefault(true);*/
            EntryForm EntryForm1 = new EntryForm(file1: main_input_source, file2: main_input_lookup, path: output_folder, file3: output_name);
            Application.Run(EntryForm1); // run program

            Environment.Exit(0); // exit program after it's run
        }
    }

我可以访问保存了其他类的其他.cs文件(即EntryForm)。另外,我看到一行包含Environment.Exit(0)的行-我试图删除此行并重新编译,但是Python脚本仍然以其他相同的方式提前终止。

通常,由于我对C#不太熟悉,所以我只是不知道从哪里开始。我不确定解决方案可能是简单的或更复杂的。希望某人能够提供各种形式的洞察力,无论大小。

如果需要,我可以尝试提供更多的C#代码。该应用程序具有很多代码,并且非常复杂,但是我会尽力而为。

谢谢!

0 个答案:

没有答案