I am trying to Execute python script from my .Net Web Application.
For this I have installed Python from nuget package manager.
Below is the Python Scrip to Insert a record in SQL Server database,
import pyodbc
conn = pyodbc.connect('DRIVER={SQL Server Native Client 11.0};SERVER=*****\SQLEXPRESS;DATABASE=TestDB;UID=sa;PWD=****')
cur = conn.cursor()
cur.execute("Insert into Results([EmailID],[Journey]) VALUES (?,?)", 55, "JourneyName")
conn.commit()
Print("Success")
Below is the C# Code to execute above python file.
public string run_cmd(string strPath) //this must not be async
{
try
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\Anaconda\python.exe";
start.Arguments = string.Format("C:\\Users\\261866\\TestPYCode.py");
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd();
string result = reader.ReadToEnd();
return result;
}
}
}
catch (Exception ex)
{
return ex.Message;
}
return "run till end";
}
I am getting below error while executing above code,
Traceback (most recent call last):
File "C:\Users\261866\TestPYCode.py", line 1, in <module>
import pyodbc
ModuleNotFoundError: No module named 'pyodbc'
I have tried same with Iron Python, but still getting same error.
Note: Same Python code is running in Jupiter notebook, but not from visual studio,
pip pyodbc libs are already installed
, ODBC drivers for SQL are installed
Actually same kind of error coming if I write any "import * " statement in python script.
Related
I want to integrate the Flask script in my asp.net web application. To Achieve this there are two methods
1) Calling the Python script using the new process with installed Python interpreter.
2) Calling the Python script using IronPython interpreter, hosted in your .NET application.
if I use simple python file it executes very well. But when I run flask python script it raises an exception "Flask Module not exist".
My question is that how can we add flask and other packages at run time
or there is any best way to run python flask script.
I have tried both ways with simple python file
1) Calling the Python script using the new process with installed Python interpreter.
2) Calling the Python script using IronPython interpreter, hosted in your .NET application.
But it raises some modules exceptions
static void Main(string[] args)
{
Console.WriteLine("Execute python Process...");
Option1_ExecProcess();
Console.ReadKey();
}
static void Option1_ExecProcess()
{
// 1) Create Process Info
var psi = new ProcessStartInfo();
psi.FileName=#"C:\Users\dell\AppData\Local\Programs\Python\Python37-
32\python.exe";
// 2) Provide script and arguments
var script=#"C:\2B_Vision______________\ReadMVP\DARC_MVP.py";
var start = "2019-1-1";
var end = "2019-1-22";
psi.Arguments = $"\"{script}\" \"{start}\" \"{end}\"";
// 3) Process configuration
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
// 4) Execute process and get output
var errors = "";
var results = "";
using (var process = Process.Start(psi))
{
errors = process.StandardError.ReadToEnd();
results = process.StandardOutput.ReadToEnd();
}
// 5) Display output
Console.WriteLine("ERRORS:");
Console.WriteLine(errors);
Console.WriteLine();
Console.WriteLine("Results:");
Console.WriteLine(results);
}
I expect just execute the python flask script with no module issues.
I am trying to Execute python script from my .Net Web Application. For this I have installed Python from nuget package manager. But I am getting following errors during execution:
I have attempted following code chunks for getting resolution but I am not able to execute it successfully.
Below is the Python Scrip to Insert a record in SQL Server database:
import pyodbc
conn = pyodbc.connect('DRIVER={SQL Server Native Client
11.0};SERVER=*****\SQLEXPRESS;DATABASE=TestDB;UID=sa;PWD=****')
cur = conn.cursor()
cur.execute("Insert into Results([EmailID],[Journey]) VALUES (?,?)", 55,
"JourneyName")
conn.commit()
Print("Success")
Below is the C# Code to execute above python file.
public string run_cmd(string strPath) //this must not be async
{
try
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\Anaconda\python.exe";
start.Arguments = string.Format("C:\\Users\\261866\\TestPYCode.py");
start.UseShellExecute = false;
start.CreateNoWindow = true;
start.RedirectStandardOutput = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd();
string result = reader.ReadToEnd();
return result;
}
}
}
catch (Exception ex)
{
return ex.Message;
}
return "run till end";
}
As I have executed above c# code I am getting below Error:
Traceback (most recent call last):"C:\Users\261866\TestPYCode.py"
import pyodbc Module Not Found Error: No module named 'pyodbc'
Error: No module named 'pyodbc'
The problem might be the source from where comes pyodbc. If your pyodbc comes from a .whl file then probably you have to install it using pip.
Here is the Microsoft's documentation says how to configure development environment for pyodbc.
Did you try it?
And here you've got ODBC Driver for SQL Server on Windows where you can download it and install.
I have a python script, changeDates.py, that successfully runs outside of a C# program started in the cmd by the command:
python changeDates.py path/to/folder numberOfMonths numberOfWeeks testSetsToCheck
These arguments are all strings. the numberOfMonths and numberOfWeeks is passed to the python script as a string then converted inside the script to an int.
But if i were to run the same command using:
private void run_CMD(string cmd, string args, bool messageBox)
{
try
{
Console.WriteLine(cmd);
Console.WriteLine(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);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error while trying to check package dates: \n" + ex);
Logger.Write(Logger.Level.ERROR, "Error while trying to check package dates: \n" + ex);
}
}
The script starts and outputs the following error:
C:\Users\bblashko\Documents\VisualStudio2012\Projects\Athena_Test_Automation_Fr
amework\Athena_Test_Automation_Framework\scripts\changeDates.py C:\Users\bblashk
o\Documents\VisualStudio2012\Projects\Athena_Test_Automation_Framework\Athena_Te
st_Automation_Framework\Test_Cases 6 1 00100
Traceback (most recent call last):
File "C:\Users\bblashko\Documents\VisualStudio2012\Projects\Athena_Test_Automa
tion_Framework\Athena_Test_Automation_Framework\scripts\changeDates.py", line 51
0, in <module>
allFiles = checkContent(content, subDir, int(sys.argv[2]), int(sys.argv[3]))
File "C:\Users\bblashko\Documents\VisualStudio2012\Projects\Athena_Test_Automa
tion_Framework\Athena_Test_Automation_Framework\scripts\changeDates.py", line 47
, in checkContent
checkXLSX(f, subDir, numberOfMonths, numberOfWeeks)
File "C:\Users\bblashko\Documents\VisualStudio2012\Projects\Athena_Test_Automa
tion_Framework\Athena_Test_Automation_Framework\scripts\changeDates.py", line 85
, in checkXLSX
changeDate = checkXLSXDates(salesStartDate, pubDate, type, todaysDate, check
Date)
File "C:\Users\bblashko\Documents\VisualStudio2012\Projects\Athena_Test_Automa
tion_Framework\Athena_Test_Automation_Framework\scripts\changeDates.py", line 15
7, in checkXLSXDates
if(re.search("(\w\w)/(\w\w)/(\w\w\w\w)", salesStartDate) and re.search("(\w\
w)/(\w\w)/(\w\w\w\w)", pubDate)):
File "C:\Python34\lib\re.py", line 166, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or buffer
Why would the regex in the python suddenly result in an error?
How can I fix this?
The string argument that you have passed to your re.search function is a python module and when you execute your python code in that way the variable string doesn't assigned correctly! So, first of all, don't use python key words and built-in names as your variable names and, to get rid of this situation, you need to check the way that you assigned the string within your code!
.NET Application and I want do execute a exe.
To this exe:
This exe file is a program to show licensed users.
I test it on my development vm with visual studio 2010 and it works but if i deploy it on the iis7 on my webserver it doens't work. The error is :
ERROR: Cannot create qrun.inf file
What is the problem? Why can't the application create the file?
Here is my code:
Web.Config:
...
<setting name="LSDYNA_CMD" serializeAs="String">
<value>~\\exe\\lstc_qrun.exe -s lwserv-lic -R</value>
</setting>
...
The exe is in my exe folder
Here I get the value:
string cmd = Properties.Settings.Default.LSDYNA_CMD;
cmd = Server.MapPath(cmd);
string output = ExecuteCommand(cmd);
...
Here is the ExecuteCommand(..) method
public static string ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
try
{
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
using (process = Process.Start(processInfo))
{
string output = process.StandardOutput.ReadToEnd();
exitCode = process.ExitCode;
return output;
}
}
catch (Exception ex)
{
return "error: " + ex.Message;
}
}
I try it on the web server directly and I get the list (O.o) I opened a cmd and make the command inside this.
I need help I don't know how I can do this :(
set writing permitions on your folder like this: IIS AppPoolIdentity and file system write access permissions
Or
You may create new folder in your ASP.NET Project and put your exe file there.
I have a python file filled with functions that I need to post using jsonrpc. Currently I can post the functions to the desired site and get results in python. But now I want to run the the python script from C#, get the results and do something with them. I am having troubles getting the python script to run and return the results to C#
I prefer to not download IronPython, so a solution that doesn't use it would be helpful.
What happens now is it there is a shell that pop ups quick then disappears when the Process.Start(start)) line is hit. Then nothing is returned to the reader.
Python Code:
#!usr/bin/python
import sys
import json
import jsonrpclib
def dc_906(orderid, givexNum, amount):
jsonrpclib.config.use_jsonclass = True
server = jsonrpclib.Server('https://dev-dataconnect.com:50')
ping1 = server.dc_906('en', orderid, 'userid', 'password', num, amount)
print jsonrpclib.history.response #this could be a "return" instead of print, not sure.
if __name__ == "__main__":
function = sys.argv[1]
orderid = sys.argv[2]
num = sys.argv[3]
amount = sys.argv[4]
if function == 'dc_906':
dc_906(orderid, num, amount)
C# code to execute the process (gotten from: How do I run a Python script from C#?)
try
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = #"C:\Python27\python.exe"; //full path to python.exe
//start.FileName = #"C:\Windows\system32\cmd.exe";
//start.Arguments = string.Format("{0} {1} {2} {3}", #"C:\Users\J1035\Documents\Python27\GiveX_python\test.py", "123456789", "603628982592000186162", 20.00);
start.Arguments = string.Format("{0} {1}", #"C:\Users\J1035\Documents\Python27\GiveX_python\test.py", "123456789 603628982592000186162 20.00");
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using(Process process = Process.Start(start))
using (StreamReader reader = process.StandardOutput)
{
string foo = reader.ReadToEnd();
TxtResultOutput.Text += foo;
}
}
catch (Exception ex)
{
var foo = ex.Message;
}
Results from running the python script on the command line:
It looks like you're forgetting the "dc_906" in your arguments line. Your function isn't being called without it.