unable to run python script from Batch file - python

Hello I Wish to run a python script, (I did not write), from a batch file I wrote.
I have 2 questions:
Running the command in the Command prompt works fine but from the batch file it fails with no error message; the python script creates an output file but it is not created when running through the batch file.
#echo off
SET /P PrePRD=Enter the Pre Production file name:
SET /P PostPRD=Enter the Post Production file name:
Set /p IdColumn= Enter the Name of the ID column (ID - Original Input):
cmd /k "cd /d C:\CSVComparison"
C:\CSVComparison\csv_diff.py -src "%PrePRD%" -dest "%PostPRD%" -keys "%IdColumn%"
I wish to open the output file which python created using Notepad++, but I'm not sure it will work this way:
start C:\Program Files (x86)\Notepad++\notepad++.exe C:\CSVComparison\results_details.json
notepad++.exe C:\CSVComparison\results_details.json
Thank you,

1) you start another instance with cmd /k, but the following command gets executed in the original instance (I guess, you want it to be executed in the second instance). Either execute it in the original instance (no cmd /... at all; you might need to call it)
pushd "C:\CSVComparison"
call "C:\CSVComparison\csv_diff.py" -src "%PrePRD%" -dest "%PostPRD%" -keys "%IdColumn%"
popd
or start it in another window:
start /d "C:\CSVComparison" "csv_diff" "C:\CSVComparison\csv_diff.py" -src "%PrePRD%" -dest "%PostPRD%" -keys "%IdColumn%"
2) if a folder or file contains space(s) , you need to enclose the whole thing in quotes. Better: get used to always enclose folders/filenames in quotes:
start "" "C:\Program Files (x86)\Notepad++\notepad++.exe" "C:\CSVComparison\results_details.json"
(start) takes the first quoted string as window title, so you need to give it a fake title ("")

Answering your first question - unfortunately Windows does (yet?) not know about shebangs, so you need to specify that you want to run your python script using python interpeter:
cmd /k "cd /d C:\CSVComparison"
C:\path\to\python.exe C:\CSVComparison\csv_diff.py -src "%PrePRD%" -dest "%PostPRD%" -keys "%IdColumn%"

Related

Can't run my script from command prompt - "too many values to unpack" [duplicate]

How can I use spaces in the Windows Command Line?
cmd /C C:\Program Files (x86)\WinRar\Rar.exe a D:\Hello 2\File.rar D:\Hello 2\*.*
Single quotation marks won't do in that case. You have to add quotation marks around each path and also enclose the whole command in quotation marks:
cmd /C ""C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*""
I just figured out that for a case where the path involves the use of white space characters, for example, when I need to access the app xyz which location is :
C:\Program Files\ab cd\xyz.exe
To run this from windows cmd prompt, you need to use
C:\"Program Files"\"ab cd"\xyz.exe
or
"C:\Program Files\ab cd\xyz.exe"
If double quotes do not solve the issue then try e.g.
dir /X ~1 c:\
to get a list of alternative file or directory names. Example output:
11/09/2014 12:54 AM 8,065 DEFAUL~1.XML Default Desktop Policy.xml
06/12/2014 03:49 PM <DIR> PROGRA~1 Program Files
10/12/2014 12:46 AM <DIR> PROGRA~2 Program Files (x86)
Now use the short 8 character file or folder name in the 5th column, e.g. PROGRA~1 or DEFAUL~1.XML, in your commands. For instance:
set JAVA_HOME=c:\PROGRA~1\Java\jdk1.6.0_45
I prefer to enclose the command in () which is valid batch which makes it a bit easier to read:
cmd /C ("C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*")
Enclose the paths containing spaces with double quotes.
cmd /C "C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*"
Try to provide complex pathnames in double-quotes (and include file extensions at the end for files.)
For files:
call "C:\example file.exe"
For Directory:
cd "C:\Users\User Name\New Folder"
CMD interprets text with double quotes ("xyz") as one string and text within single quotes ('xyz') as a command.
For example:
FOR %%A in ('dir /b /s *.txt') do ('command')
FOR %%A in ('dir /b /s *.txt') do (echo "%%A")
And one good thing, cmd is not* case sensitive like bash. So "New fiLE.txt" and "new file.TXT" is alike to it.
*Note: The %%A variables in above case is case-sensitive (%%A not equal to %%a).
set "CMD=C:\Program Files (x86)\PDFtk\bin\pdftk"
echo cmd /K ""%CMD%" %D% output trimmed.pdf"
start cmd /K ""%CMD%" %D% output trimmed.pdf"
this worked for me in a batch file
Just add Quotation Mark
Example:"C:\Users\User Name"
Hope it got Solved!
Spaces in the Commend Prompt (in a VBA Shell command code line)
I had a very similar problem which ended up being a space in the command prompt when automating via VBA to get the contents from the command window into a text file. This Thread was one of many I caught along the way that didn’t quite get me the solution.
So this may help others with a similar problem: Since the syntax with quotes is always difficult to get right , I think showing some specific examples is always useful.
The additional problem you get using the command prompt in VBA via the Shell thing, is that the code line often won’t error when something goes wrong: in fact a blink of the black commend window misleads into thinking something was done.
As example… say I have a Folder, with a text file in it like at
C:\Alans Folder\test1.txt ( https://imgur.com/FELSdB6 )
The space there in the folder name gives the problem.
Something like this would work, assuming the Folder, AlansFolder, exists
Sub ShellBlackCommandPromptWindowAutomatingCopyingWindowContent()
Shell "cmd.exe /c ""ipconfig /all > C:\AlansFolder\test1.txt"""
End Sub
This won’t work. (It won’t error).
Sub ShellBlackCommandPromptWindowAutomatingCopyingWindowContent()
Shell "cmd.exe /c ""ipconfig /all > C:\Alans Folder\test1.txt"""
End Sub
Including quote pairs around the path will make it work
Sub ShellBlackCommandPromptWindowAutomatingCopyingWindowContent()
Shell "cmd.exe /c ""ipconfig /all > ""C:\Alans Folder\test1.txt"""""
End Sub
( By the way, if the text file does not exist, then it will be made).
With the benefit of hindsight, we can see that my solution does tie up approximately with some already given..
Converting that code line to a manual given command we would have
ipconfig /all > "C:\Alans Folder\test1.txt"
That seems to work
This works also
ipconfig /all > C:\AlansFolder\test1.txt
This doesn’t
ipconfig /all > C:\Alans Folder\test1.txt
This final form also works and ties up with the solution from sacra ….” You have to add quotation marks around each path and also enclose the whole command in quotation marks “ …..
cmd.exe /c "ipconfig /all > "C:\Alans Folder\test1.txt""
You should try using quotes.
cmd /C "C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*"
It can solve this problem by cd command, this command understand spaces without double quotes and you can call any program this way for example:
C:\Windows\system32>cd c:\Program Files\MongoDB\Server\3.2\bin
c:\Program Files\MongoDB\Server\3.2\bin>mongo
now command prompt call mongo.exe

Is there a way to have Windows task scheduler automatically respond to input() in Python script?

I'm trying to schedule a python script to run automatically on a Windows 10 machine. The script, when run alone, prompts the user for some input to use as it runs. I'd like to automatically set these inputs when the scheduler runs the .bat file. As an example:
test.py:
def main():
name = input('What is your name? ')
print(f'Hello, {name}. How are you today?')
main()
This works fine if I just run the script, but ideally I'd like to have the name variable passed to it from the .bat file.
test.bat:
"path\to\python.exe" "path\to\test.py"
pause
Any help would be greatly appreciated!
If you just want to give a single fixed input, you can do it like:
REM If you add extra spaces before `|` those will be passed to the program
ECHO name_for_python| "path\to\python.exe" "path\to\test.py"
Unfortunately, there is no good way of extending this to multiple lines. You would use a file containing the lines you want to input for that:
"path\to\python.exe" "path\to\test.py" < file_with_inputs.txt
If you want to have everything into a standalone script, you may do something like this:
REM Choose some path for a temporary file
SET temp_file=%TEMP%\input_for_my_script
REM Write input lines to file, use > for first line to make sure file is cleared
ECHO input line 1> %temp_file%
REM Use >> for remaining lines to append to file
ECHO input line 2>> %temp_file%
ECHO input line 3>> %temp_file%
REM Call program with input file
"path\to\python.exe" "path\to\test.py" < file_with_inputs.txt
REM Delete the temporary file
DEL %temp_file% /q
Obviously, this is assuming you cannot use the standard sys.argv (or extensions like argparse), which would be the more standard and convenient way to send arguments to a script.

Passing argument to python script within a batch file in Windows

I have a python script that can be called in Windows as:
python.exe do_my_work.py param > output.csv
param is an input parameter.
I also have a txt file called params.txt that contains many lines, each line is a value for the parameter of the python script:
hello
world
this
is
test
Because params.txt consists of many many lines, so I would like to write a .batch file that read params.txt line by line then calls python script with the read line as the parameter. The pseudo code as:
open params.txt;
while !eof do:
read a line;
call "python.exe do_my_work.py $line >> output.csv";
end while;
close params.txt;
Could you please show me how to solve this.
P/S: I don't want to change do_my_work.py source code due to some special reasons.
#echo off
set "params=C:\params.txt"
set "output=output.csv"
for /f "usebackq tokens=* delims=" %%# in ("%params%") do (
python do_my_work.py %%# 1>>"%output%"
)

python subprocess module can't parse filename with special characters "("

I have a Python program that reads files and then tars them into tar balls of a certain size.
One of my files not only has spaces in it but also contains parentheses. I have the following code:
cmd = "/bin/tar -cvf " + tmpname + " '" + filename + "'"
NOTE: Those are single quotes inside double quotes outside of the filename variable. It's a little difficult to see.
Where tmpname and filename are variables in a for-loop that are subject to change each iteration (irrelevant).
As you can see the filename I'm tarballing contains single quotes around the file name so that the shell (bash) interprets it literally as is and doesn't try to do variable substitution which "" will do or program execution which ` will do.
As far as I can see, the cmd variable contains the exact syntax for the shell to interpret the command as I want it to. However when I run the following subprocess command substituting the cmd variable:
cmdobj = call(cmd, shell=True)
I get the following output/error:
/bin/tar: 237-r Property Transport Request (PTR) 012314.pdf: Cannot stat: No such file or directory
/bin/tar: Exiting with failure status due to previous errors
unable to tar: 237-r Property Transport Request (PTR) 012314.pdf
I even print the command out to the console before running the subprocess command to see what it will look when running in the shell and it's:
cmd: /bin/tar -cvf tempname0.tar '237-r Property Transport Request (PTR) 012314.pdf'
When I run the above command in the shell as is it works just fine. Not really sure what's going on here. Help please!
Pass a list of args without shell=True and the full path to the file if running from a different directory:
from subprocess import check_call
check_call(["tar","-cvf",tmpname ,"Property Transport Request (PTR) 012314.pdf"])
Also use tar not 'bin/tar'. check_call will raise a CalledProcessError if the command returns a non-zero exit status.
The call method that is part of the subprocess module should have an array of strings passed.
On the command line you would call
tar -cvf "file folder with space/"
The following is equivalent in python
call(["tar", "-cvf", "file folder with space/"])
You are making this call in the shell
"tar -cvf 'file folder with space/'"
Which causes the shell to look for a program with the exact name as `tar -cvf 'file folder with space/'
This avoids string concatenation, which makes for cleaner code.

Python not outputing to file when script is run in vb program

I am making a vb text editor that can run scripting code. I have successfully gotten it to run the code and show up but I would like to be able to have the output from the the code redirected to a file without having to do anything to the python code. Is that possible?
This is the code I'm using to try it but it does not write anything to the file:
Shell(compiler & " """ & fileName & " "" > C:\output.txt")
the compiler is the location of python.exe in the python install folder and the file name is the file I'm running.
The problem could also be in the way I am trying to do it with the shell command.
After some more research into the the matter I found a way to make it work.
Here is the working code:
Shell("cmd.exe /c " & compiler & " """ & fileName & " "" > ""C:\output.txt"" ", vbNormalFocus)
So I am actually running the line through the command prompt which is being called by the shell function. My assumption was that shell function was using the command prompt to execute the string argument but I guess I was wrong. Also, just to note, the output file name is also surrounded by quotes which is different than my original post.

Categories

Resources