简体   繁体   English

如何从C#向Python脚本传递双引号作为参数?

[英]How do you pass a double quote as an argument to python script from C#?

My ultimate goal, is to pass a 'json string' from C# to python script. 我的最终目标是将“ json字符串”从C#传递到python脚本。

For instance, in python script, I would like to get as sys.argv[1], something along these lines: 例如,在python脚本中,我想得到sys.argv [1],大致如下:

'{"A":"Hello", "B":"world"}'

Then, I would be able to use: 然后,我将可以使用:

mystring = sys.argv[1]
myjson = json.loads(mystring)

I am not able to get the above. 我无法获得以上。 And so, I even tried just getting this: 所以,我什至尝试得到这个:

{"A":"Hello", "B":"world"}

(so that, I could add the first and last single quotes manually in python). (这样,我可以在python中手动添加第一个和最后一个单引号)。

Unfortunately, in either case, I am unable to pass the double quotes. 不幸的是,无论哪种情况,我都无法使用双引号。

In C#, I have tried: 在C#中,我尝试过:

string myarguments = "main.py \"{\"A\":\"Hello\", \"B\":\"world\"}\"";
var myProcessStartInfo = new ProcessStartInfo(Path_OF_PYTHON_EXE);
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.Arguments = myarguments;
var myProcess = new Process();
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();

The part I am struggling with is to get the correct string myarguments that will allow the python script to receive a double quote as an argument. 我苦苦挣扎的部分是获得正确的字符串myarguments ,它将允许python脚本接收双引号作为参数。

With the above C# snippet, the python script: 使用上面的C#代码段,python脚本:

import sys
print(str(sys.argv))
print('arg0 : ' + sys.argv[0])
print('arg1 : ' + sys.argv[1])

prints the following: 打印以下内容:

['main.py', '{A:Hello, B:world}']
arg0 : main.py
arg1 : {A:Hello, B:world}

What I really want in python, is to get from the line: print('arg1 : ' + sys.argv[1]): 我在python中真正想要的是从这一行得到:print('arg1:'+ sys.argv [1]):

arg1 : {"A":"Hello", "B":"world"}

Or even better: 甚至更好:

arg1 : '{"A":"Hello", "B":"world"}'

I have tried many other scenarios (trying to escape double quotes in C#), but none of them gave me the correct sys.argv in python. 我尝试了许多其他情况(试图在C#中转义双引号),但是没有一个给我python中正确的sys.argv。 Any help on this is very appreciated! 非常感谢您的任何帮助!

I have figured out the way: 我想出了办法:

In C#: 在C#中:

string myarguments = "main.py \"{\"\"A\"\":\"\"Hello\"\", \"\"B\"\":\"\"world\"\"}\" ";

In python, print(str(sys.argv)) prints: 在python中,print(str(sys.argv))打印:

['main.py', '{"A":"Hello","B":"world"}']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM