Calling Python (anaconda) with Batch File from ASP.NET - python

I am trying to call a python script from my asp.net web app. I am using a batch file to call the python script. The python script runs from the batch file when I run it on the server. When I try to call the batch file from asp.net, the code in the batch file works until it gets to the call for the python, and the call to the python script doesn't work.
This is my batch file:
(
echo Hello
)
C:\inetpub\Sites\**\**\**\test.txt
rem the code above works from ASP.NET
rem this code is never called
set CONDAPATH="C:\\Users\\***\\Anaconda3"
set ENVNAME="base"
if %ENVNAME%==base (set ENVPATH=%CONDAPATH%) else (set ENVPATH=%CONDAPATH%\envs\%ENVNAME%)
call %CONDAPATH%\Scripts\activate.bat %ENVPATH%
C:\\Users\\***\\Anaconda3\\python.exe C:\\inetpub\\Sites\\**\\***\\testfolder\\try_py.py
Could anyone help me figure out what I am doing wrong in calling this python code?

The first thing you need to understand is that your line:
C:\inetpub\Sites\**\**\**\test.txt
will open a text file in the default application for doing so, and your script will then wait until you have closed that text file, before it continues to the next line. If you want the code to continue without waiting for the text file to be closed, you can use the start command:
Start "" "C:\inetpub\Sites\**\**\**\test.txt"
Here's a quick example to demonstrate my earlier comment, regarding the recommended syntax for defining variables, and using doublequotes around file paths.
Set "CONDAPATH=%UserProfile%\Anaconda3"
Set "ENVNAME=base"
If /I "%ENVNAME%" == "base" (Set "ENVPATH=%CONDAPATH%") Else Set "ENVPATH=%CONDAPATH%\envs\%ENVNAME%"
Call "%CONDAPATH%\Scripts\activate.bat" "%ENVPATH%"
"%CONDAPATH%\python.exe" "C:\\inetpub\\Sites\\**\\***\\testfolder\\try_py.py"
Putting it all together:
#Echo Off
Echo Hello
Start "" "C:\inetpub\Sites\**\**\**\test.txt"
Set "CONDAPATH=%UserProfile%\Anaconda3"
Set "ENVNAME=base"
If /I "%ENVNAME%" == "base" (Set "ENVPATH=%CONDAPATH%") Else Set "ENVPATH=%CONDAPATH%\envs\%ENVNAME%"
Call "%CONDAPATH%\Scripts\activate.bat" "%ENVPATH%"
"%CONDAPATH%\python.exe" "C:\\inetpub\\Sites\\**\\***\\testfolder\\try_py.py"
If you don't want the script to wait until the python command has completed, (for instance, if this is the last line of your script), you could change that last line to:
Start "" "%CONDAPATH%\python.exe" "C:\\inetpub\\Sites\\**\\***\\testfolder\\try_py.py"

I figured it out in case anyone is still using asp.net like me. It was all a permissions issue on my folder that had I was calling the python script from CONDAPATH="C:\Users\***\Anaconda3".
This link gave me the hint: IIS7 Permissions Overview - ApplicationPoolIdentity

Related

Why doesn't the rest of the code after call() work? [duplicate]

I have a python script which when run, logs information on the terminal, i want to send this logging information to a text file,
To achieve this in the beginning of the file i am inserting
import subprocess
subprocess.call(['script', 'logfile'])
and at the end of the file,i put in,
subprocess.call(['exit'])
The problem with this is when it calls the first commandscript logfile,it terminates the script,
Any suggestions on how i could make this work would be really helpful,Thanks in advance
The problem is that subprocess.call isn't returning until the shell spawned by script exits, at which point your Python script will resume.
The simplest way to do what you want is to call script itself with your Python script as an argument. Instead of
#!/usr/bin/python
import subprocess
subprocess.call(['script', 'logfile'])
# Rest of your Python code
subprocess.call(['exit'])
you will use
#!/usr/bin/python
import os
import sys
if '_underscript' not in os.environ:
os.environ['_underscript'] = "yes"
cmd_args = ['script', 'logfile', 'python'] + sys.argv
os.execvp('script', cmd_args)
# Rest of your Python code
The environment variable prevents your script from entering an infinite loop of re-running itself with script. When you run your Python script, it first checks its environment for a variable that should not yet exist. If it doesn't, it sets that variable, then runs script to re-run the Python script. execvp replaces your script with the call to script; nothing else in the Python script executes. This second time your script runs, the variable _underscript does exist, meaning the if block is skipped and the rest of your script runs as intended.
Seems like that's the expected behaviour of subprocess.call(...). If you want to capture the output of the script to a file, you'll need to open a new file handler in write mode, and tell the subprocess.call where to direct the stdout, which is the terminal output you typically would see.
Try:
import subprocess
f = open('/tmp/mylogfile.log', 'w')
subprocess.call(['/path/to/script'], stdout=f)
f.close()
Then in the terminal you can run tail /tmp/mylogfile.log to confirm.
I'm not sure the last exit call is required for what you're trying to achieve.
You can read more in the python docs, depending which version of Python you're using. https://docs.python.org/2/library/subprocess.html
The file doesn't need to pre-exist. Hope that helps!

Monitor a directory for added files [duplicate]

This question already has an answer here:
Monitoring directory with VB Script
(1 answer)
Closed 7 years ago.
I've written in .vbs .bat and .au3 before, so I know a little about scripting. What I'm after is a file (in any of the above languages) that will monitor a directory (Let's just say "C:\Users\User\Desktop\Folder") for files (only .html), and then, when a new file is added it will run a new batch file. My only necessity for this is that it runs in the background, with no command window, from what I know and what I've read, .bat won't allow this, and I can't seem to figure out how to do this with .au3 (AutoIt). I'm totally open to new languages, the "inotifywait" from python was suggested, but I've never written in python. All other questions I've read have been for servers, but I just want this all locally done. If someone could please either provide a script for this, or point me towards a link, question, help file or anything else so I could learn this, that would be amazing.
#echo off
setlocal
:start
set inputFolder=%1"C:\Users\Zac\Dropbox\SoundCloud"
set extension=%2html
IF EXIST %inputFolder%\*.%extension% GOTO exists
goto end
:end
goto start
:exists
timeout 70 > NUL
call Random.bat
goto start
Is my script so far, this works, kind of, this requires me to press a key before continuing, and requires me to do so every time we go to :start, and has a command window.
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd /k dir c:\windows\*.*", 0, false
This starts a hidden command prompt (the 0).
If you want it all in vbs see wscript.sleep command and here's how to delete, test, and copy files. Also how to start a program.
Set Sh = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists("C:\Users\David Candy\Desktop\nethack-360-win-x86-2\bonD0.O") then fso.deletefile "C:\Users\David Candy\Desktop\nethack-360-win-x86-2\bonD0.O"
If fso.FileExists("C:\Users\David Candy\Desktop\nethack-360-win-x86-2\David%20Candy-David.NetHack-saved-game") then
fso.copyfile "C:\Users\David Candy\Desktop\nethack-360-win-x86-2\David%20Candy-David.NetHack-saved-game", "C:\Users\David Candy\Desktop\nethack-360-win-x86-2\David%20Candy-David - Copy.NetHack-saved-game"
else
fso.copyfile "C:\Users\David Candy\Desktop\nethack-360-win-x86-2\David%20Candy-David - Copy.NetHack-saved-game", "C:\Users\David Candy\Desktop\nethack-360-win-x86-2\David%20Candy-David.NetHack-saved-game"
end If
sh.run """C:\Users\David Candy\Desktop\nethack-360-win-x86-2\NetHackW.exe""", 1

Python - Running just a single line of code, and not the rest of the Multiple lines in the Script

In - Python, inside the the IDLE, in the File Editor Window,
How do you run just a selected single line of code in the script, without having the rest of the lines of the program being runned ?
You'll have to run your line of code form command line:
With the -c (command) argument (assuming your file is named foo.py):
$ python -c 'import foo; print foo.hello()'
You can select and copy a single statement in an Idle editor (or anywhere else, for that matter), switch to the Idle Shell, and paste on the line with the >>> prompt as the bottom. (You can hit to get a clean prompt.) Then hit return just as it you had entered into the shell directly. This works for multiline statements. Being able to do this with a menu selection, hotkey, or right-click selection is on my todo list, as you are not the first to ask about this.
Basically, what we call "debugger" should be fulfilled your requirement. Many IDEs are provided "debugger tools" including IDLE. To use a debugger tool you can just simply
add break lines (any lines of code you want a program to stop while program is running),
explore your variables (when program is stop you can print out values of your variables at that time)
Click/type step to go to the next breakpoint.
This is just a roughly procedure that should be fit to your requirement.
see more: debug

How to disable creating a new python IDLE session when compiling through Notepad++?

when I'm compiling python through Notepad++ I get a new python shell ( IDLE ) everytime, but I rather just keep one fixed window, instead of a new window on another position.
So for example, when I write a script which prints "Hello World!" and compile it so that my Python Shell displays the text, and when I modify my script to "Goodbye World!" the same shell prints that text. Or that that shell gets closed, but that at the same position a new shell emerges with the new text.
Could somebody please help me I'm having a hard time figuring this out..
Many thanks in advance!
You might have noticed, that python source code does not require a compilation to get run. Python source-code is rather beeing interpreted on-the-fly, by the language "engine".
Your issue is related with the Notepad++ settings and O/S settings.
IDLE is a program, that has typically been set in O/S as an associated-application to a set of filename-extensions ( .py, etc )
If your Notepad++ Compile does not call O/S to "launch" a file, the problem ceases to exist.
Your normal step to "run" the file then would be to just re-type inside the python terminal, whenever you have saved any code-modification in Notepad++:
>>> execfile( "<<_whatever_filename_my_python_source_has_>>" ) # local DIR
>>> execfile( "C:\\someDIR\\anotherSubDIR\\runMyPYTHON.py" ) # doubled-slashes

How to use a value in a python script to setup an environment variable

I am having the following issue setting up an enviroment variable,looked at other examples set environment variable in python script ,one worked
1.I have a value in variable "version" in a python script.
2.Now,I need to set this as enviroment variable for BUILD_VER in windows(currently its in windoWs,prefer to make it generic across OS),normally a simple SET BUILD_VER=%version% in a batch file would do(this enviroment variable is used by another batchfile which makes a software build which I guess is unrelated here)
Now,coming and focusing to the problem.
Is there a way I can set BUILD_VER =VERSION in the same python script and pass it onto a batch file?any other ideas?i tried the following in a batch file but am not sure if the python script is running ?running the following doesnt output anything
#echo off
FOR /F %v IN ('build_ver.py 123637') DO SET BUILD_VER=%v
You have not clearly specified the inter-relation of the several batch files and your python script, so lets analyze some of the possibilities:
The python script define the variable, execute a batch file that set the same variable and then the python script continue by itself and execute other batch files that you want have access to the variable defined in the first batch file. This is just not possible. Period.
The python script define the variable, execute the batch file that set the same variable and then the batch file continue and execute other batch files that inherits the variable. Perfectly valid. In this case the python script is just used to define the variable and start the first batch file.
The first batch file start execution, execute the python script just to get the value of the variable, define it and execute other batch files that inherits the variable. This is the simplest solution; in this case the python script is used only to get the value of the variable.
The way to implement the last solution is like in your example:
#echo off
rem Execute python script passing to it the first parameter of this Batch file
FOR /F %%v IN ('build_ver.py %1') DO SET BUILD_VER=%%v
echo Value defined by python script: %BUILD_VER%
rem Call another Batch file that inherits this variable:
call AnotherBatch.bat
Note that in your code you missed a couple of percent signs in the FOR /F command...

Categories