您的位置:首页 > 汽车 > 新车 > python-调用c#代码

python-调用c#代码

2025/2/23 14:10:43 来源:https://blog.csdn.net/pxy7896/article/details/140928774  浏览:    关键词:python-调用c#代码

环境:
win10,net framework 4,python3.9


镜像:
C#-使用IronPython调用python代码_ironpython wpf-CSDN博客
https://blog.csdn.net/pxy7896/article/details/119929434


目录

  • hello word
    • 不接收参数
    • 接收参数
  • 其他例子

hello word

不接收参数

hello.cs内容如下:

using System;class HelloWorld
{static void Main(){Console.WriteLine("hello world");}
}

python调用:

>>> import subprocess
>>> subprocess.call(['C:/Windows/Microsoft.NET/Framework64/v4.0.30319/csc.exe', 'hello.cs'])
Microsoft (R) Visual C# Compiler version 4.8.4084.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=5332400
>>> result = subprocess.run(['hello.exe'],capture_output=True,text=True)
>>> result.stdout
'Hello, World!\n'

说明:

  1. subprocess.call后,当前路径会产生一个hello.exe,双击没有反应
  2. subprocess.call的第一个参数可能要根据实际情况修改,此处只是我本机的安装路径,仅作参考
  3. 使用subprocess.run才是真正执行,可以反复run

接收参数

修改C#:

using System;class HelloWorld
{static void Main(string[] args){Console.WriteLine(args[0] + " " + args[1]);}
}

python调用的时候就需要带参数:(当然要先call制作新的exe)

>>> result = subprocess.run(['hello.exe', "hello", "world"],capture_output=True,text=True)
>>> result.stdout
'hello world\n'

其他例子

待补充

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com