|
Answer» Hi all, Im writing a batch program that opens python files. Basically, if the person doesnt drag a python file onto the batch it asks them for a path, if the file doesnt exist they have to type it again(if they type nothing it opens the interpreter). However, no matter what file path i type, right or wrong, it always says the file doesnt exist...
Code: [Select]@Echo off cd C:\Python27
IF (%1) == () GOTO GETFILE ELSE GOTO HAVEFILE
:GETFILE Set /p file=Choose a file: IF (%file%) == () GOTO HAVEFILE IF NOT EXIST (%file%) echo No file found Set file= GOTO GETFILE CLS python %file% pause
:HAVEFILE CLS python %1 pause Any advice?Dump those brackets. Use double quotes like most PEOPLE. What made you use brackets anyway? They are useful in the IF (x) == () tests, where they detect null variables, but you cannot use them with a variable which is being passed to the SYSTEM as a filename. Suppose %file% expands to myfile.py then when you run IF NOT EXIST (%file%) you are asking the system if a file named (myfile.pi) -- complete with brackets -- exists. This does not happen with quotes which are good for accommodating filenames with spaces as they are stripped off by the system. So use double quotes for both tasks.
Code: [Select]IF NOT EXIST "%file%" echo No file found
Perfect! Thankyou! I havent made a batch file in a while, i knew to use brackets on the IF statements i just assumed it would be the same for the IF EXIST Quote from: jpotts on May 13, 2012, 01:42:22 PM Perfect! Thankyou! I havent made a batch file in a while, i knew to use brackets on the IF statements i just assumed it would be the same for the IF EXIST
You don't have to use brackets around the things being compared in IF statements. You can use most of the character set EXCEPT for the special characters such as <>& etc. Most people use double quotes like this
IF "%variable%" == ""
IF "%animal%" == "horse"
etc
Oh, i didnt know that. Thanks!In fact you don't have to use anything surrounding a variable if you are comparing one thing with another e.g.
if %animal% == horse if %var1% == %var2%
etc.
If you use bare variables you will be all right until one of them happens to be blank in which case the script will fail, which is why many batch CODERS routinely surround them with quotes or other characters in IF tests. Just keep the other characters away from filenames.
Of course you do need to surround the variable if you are comparing one thing with nothing (a blank)
if "%animal%" == "" if .%animal%. == .. if [%animal%] == []
|