首页 > 解决方案 > 如何在没有 IronPython 的情况下将 C#(winforms 应用程序)、当前文本框文本传递给 Python 变量

问题描述

我目前正在尝试通过 process.start() 将变量从我的 C# winforms 应用程序传递给我的 Python 可执行文件。该脚本使用shutil复制和重命名一个单独的python文件,该文件将根据变量(var,c#变量)重命名...

我的问题是为我的 Python 脚本定义 C# 变量当前值或值。我的 Windows 窗体应用程序与当前脚本完美运行,但当我尝试运行我的 Python 脚本并通过“.Arguments”传递 C# 变量时,我的 Python 文件返回“NameError: name 'Textboxpath' is not defined”。我试图重写 process.start() 函数,包括我的python脚本中的变量,定义变量没有成功,任何帮助将不胜感激!

**C#:**
...
#script for defining openFileDialog variable and using OpenFileDialog goes here
Textboxpath.Text = openFileDialog.FileName; #prints file (excel workbook) directory path to text box
...
string var;
var = Textboxpath.Text;
ProcessStartInfo StartInfo
    = new ProcessStartInfo(@"C:\directorytask\dist\modifyfest.exe");
StartInfo.FileName = "C:\\directorytask\\dist\\modifyfest.exe";
StartInfo.Arguments = var;
Process.Start(StartInfo);

**Python script: modifyfest.exe** #packaged with pyinstaller, --onefile
import os
import sys
import shutil

x = var
f = x - '.xlsx'
l = f - 'C:\directorytask'
k = '.py'
y = 'test_'
z = y + l +k
#duplicating/renaming python file
original = 'C:/directorytask/test_five.py' #original python file
target = 'C:/directorytask/' + z   #original python file being duplicated with name z
shutil.copyfile(original, target)

**Error:**

Traceback <most recent call last>:
  File "modifyfest.py", line 5, in <module>
NameError: name 'Textboxpath' is not defined
[34652] failed to execute script modifyfest

标签: pythonc#winformsprocessundefined

解决方案


我添加了解析器!这就是 Python 脚本现在的样子,运行完美......

**answer:**
import os
import sys
import shutil
from pathlib import Path

def parse(p):
    q = p
    return q

x = parse(sys.argv[1]) #imports first argument sent by c#, I attempted sys.argv[0] instead and it returned the first line of my c# ProcessStartInfo list, file name...
p = Path(x).stem
k = '.py'
y = 'test_'
z = y + p +k

original = 'C:/directorytask/test_five.py' #retailer specific duplicated task
target = 'C:/directorytask/' + z   #task being created
shutil.copyfile(original, target)

推荐阅读