I keep getting a syntax error against the "C" in "C:\Users".
`#! python3
print('Hello world')`
#C:\Users\AK\MyPythonScripts>py.exe hello.bat
# File "hello.bat", line 1
# #py C:\User\AK\MyPythonSctipts\hello.py %*
# ^
#SyntaxError: invalid syntax
I've tried adding "\". I can't figure it out. Following along in "Automate the Boring Stuff." (Lesson 22)
#I keep getting a syntax error against the "C" in "C:\Users".
`#! python3
print('Hello world')`
#C:\Users\AK\MyPythonScripts>py.exe hello.bat
# File "hello.bat", line 1
# #py C:\User\AK\MyPythonSctipts\hello.py %*
# ^
#SyntaxError: invalid syntax
I expect to run the batch file and added a "#pause" feature, but the program won't execute since "C" is an invalid syntax.
May not the perfect answer you are looking for, but let me share in general essense how you run a python script in windows.
Open Command line: Start menu -> Run and type cmd
Type: C:\python27\python.exe C:\Users\Awesome\Desktop\Adel.py
In your system, your python .exe location might a bit different or you could be using python3, but overall format is specify you python exe first followed by your script's full path (<python.exe> <python-script-full-path>
I figured it out! My command prompt path wasn't set properly. I went to "My Computer" -> right-click -> Properties -> Advanced System Settings and changed my environment variable.
Related
I want to use Python to open a directory in a Win10 cmd window, and keep the window open.
I made a batch file named: open_dir_in_cmd_window.CMD:
CD /D %1
I tested that batch file successfully, by creating another batch file named, Test.cmd:
Rem "open_dir_in_cmd_window.CMD" "f:\backup"
"open_dir_in_cmd_window.CMD" "f:\backup"
A very helpful webpage provides the following example, which I seem unable to follow correctly:
Spaces in Program Path + parameters with spaces:
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
I made a python script, which contains the following lines, which alas, triggers an error message:
import subprocess
subprocess.run(cmd /k "E:\open_dir_in_cmd_window.CMD f:\backup")
When I open a Command Prompt window and run:
"C:\ProgramData\Anaconda3\python.exe" E:\open_dir.py
I get an error message, SyntaxError: invalid syntax, with this:
subprocess.run(cmd /k "E:\open_dir_in_cmd_window.CMD f:\backup")
^
I've tried many different permutations of double quoting and can't figure out the right way to do it.
I have spent many hours hunting on the web and trying to figure this out and I do not know what to do.
Any suggestions would be appreciated.
Does any one know why i got an error of "FileNotFoundError: [Errno 2] No such file or directory: 'bcs.xlsx'" when i'm loading this file of size 2mb it has around 60,000 rows and 4 columns.
i tried using csv instead of xlsx but i get the same error and i've checked hundreds times that the script and the file are at he same directory.
This is because Python does not find your file, errors are not lying.
But there's a misunderstanding in your question, you checked that the file is in the same directory as your script, but that's not the check you have to do. You have to check the file is in the current working directory of your python script.
To see your current working directory, use:
import os
print(os.getcwd())
And as we're at it you can list this directory:
print(os.listdir())
I don't know how you execute your script, but if you're using a terminal emulator, a typical way to give a file name to a program is by argument, not hardcoding its name, like by using argparse. And if you do this way, your shell completion may help you naming your file properly, like:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()
print(args.file.read())
Now on a shell if you type:
python3 ./thescript.py ./th[TAB]
your shell will autocomplete "./th" to "./thescript.py" (if and only if it exists), highly reducing the probablity of having a typo. Typically if there's a space in the filename like "the script.py", your shell should properly autocomplete the\ script.py.
Also if you use argparse with the argparse.FileType as I did, you'll have a verbose error in case the file does not exist:
thescript.py: error: argument file: can't open 'foo': [Errno 2] No such file or directory: 'foo'
But… you already have a verbose error.
I wrote the following for a homework assignment and it works fine in IDLE and Eclipse running Python 3.
However, I tried to run it from TextMate with the new line 1 -- which I found here -- to point it to Python 3 on the Mac. It seems to be running Python 3 but returns an error. It says: EOFError: EOF when reading a line. It's referring to line 5 below.
Anyone know why?
BTW, this TextMate issue is not part of the homework assignment, so I'm not trying to get homework help. I just want to figure out how to use TextMate with Python 3.
#! /usr/local/bin/python3
#
# Tests user string against two conditions.
#
user_string = input("Enter a string that is all upper case and ends with a period: ")
if user_string.isupper() and user_string.endswith("."):
print("Your string met both conditions.")
else:
if user_string.isupper():
print("Your string does not end with a period.")
elif user_string.endswith("."):
print("Your string is not all upper.")
else:
print("Your string failed both conditions.")
The problem you are seeing has nothing to do with the Python version. The problem is that TextMate does not try to redirect standard input so, when you are running via the TextMate's Python bundle Run Script command, the Python program sees an immediate end-of-file. As explained here, TextMate used to be fancier about this but the mechanism it used no longer works in OS X 10.6 so the feature was disabled.
One solution is to use the Shift-Command-R Run Script in Terminal command of TextMate's Python bundle. This causes TextMate to open a terminal window and run the script there and you can enter the input there. Unfortunately, while TextMate does respect the shebang line with the normal Command-R Run Script command, it doesn't seem to do so with the Run Script in Terminal command. You can verify that yourself in various ways. Try running this code snippet in TextMate:
#! /usr/local/bin/python3
import sys
print(sys.executable)
To get around that, you can set the TM_PYTHON environment variable in TextMate. See the answer here for more details on how to do that.
Textmate is using the built-in Python, rather than respecting the shebang line. You'd probably have to hack the bundle code to use the right python.
I've set up slimv with the following command in vim:
let g:slimv_swank_cmd = '!gnome-terminal -e "sbcl --load ~/.vim/bundle/slimv/slime/start-swank.lisp &"'
When opening .lisp files and starting slimv, I recieve the following error message in the newly opened terminal window:
debugger invoked on a SB-INT:SIMPLE-FILE-ERROR in thread
#<THREAD "main thread" RUNNING {1002A8B203}>:
Couldn't load #P"~/.vim/bundle/slimv/slime/start-swank.lisp": file does not exist.
Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [CONTINUE] Ignore runtime option --load "~/.vim/bundle/slimv/slime/start-swank.lisp".
1: [ABORT ] Skip rest of --eval and --load options.
2: Skip to toplevel READ/EVAL/PRINT loop.
3: [EXIT ] Exit SBCL (calling #'EXIT, killing the process).
(LOAD #P"~/.vim/bundle/slimv/slime/start-swank.lisp" :VERBOSE NIL :PRINT NIL :IF-DOES-NOT-EXIST T :EXTERNAL-FORMAT :DEFAULT)
However, running the sbcl command from the terminal works properly because the file does exist on the path specified. How can I fix this issue?
You need to make sure that the tilde gets expanded. Expansion is provided by the shell.
You can also compute the pathname in Common Lisp using:
(merge-pathnames ".vim/bundle/slimv/slime/start-swank.lisp"
(user-homedir-pathname))
-> #P"/home/foobar/.vim/bundle/slimv/slime/start-swank.lisp"
Merging a relative pathname with an absolute pathname, adds the directory like above.
Both functions (merge-pathnames and user-homedir-pathname) are in the ANSI CL standard.
I would like to easily test my python programs without constantly using the python shell since each time the program is modified you have to quit, re-enter the python shell and import the program again. I am using a 2012 Macbook pro with OSX. I have the following code:
import sys
def read_strings(filename):
with open(filename) as file:
return file.read().split('>')[1:0]
file1 = sys.argv[1]
filename = read_strings(file1)
Essentially I would like to read into and split a txt file containing:
id1>id2>id3>id4
I am entering this into my command line:
pal-nat184-102-127:python_stuff ceb$ python3 program.py string.txt
However when I try the sys.argv approach on the command line my program returns nothing. Is this a good approach to testing code, could anyone point me in the correct direction?
This is what I would like to happen:
pal-nat184-102-127:python_stuff ceb$ python3 program.py string.txt
['id1', 'id2', 'id3', 'id4']
Let's take this a piece at a time:
However when I try the sys.argv approach on the command line my
program returns nothing
The final result of your program is that it writes a string into the variable filename. It's a little strange to have a program "return" a value. Generally, you want a program to print it's something out or save something to a file. I'm guessing it would ease your debugging if you modified your program by adding,
print (filename)
at the end: you'd be able to see the result of your program.
could anyone point me in the correct direction?
One other debugging note: It can be useful to write your .py files so that they can be run both independently at the command line or in a python shell. How you've currently structured your code, this will work semi-poorly. (Starting a shell and then importing your file will cause an error because sys.argv[1] isn't defined.)
A solution to this is to change your the bottom section of your code as follows:
if __name__ == '__main__':
file1 = sys.argv[1]
filename = read_strings(file1)
The if guard at the top says, "If running as a standalone script, then run what's below me. If you imported me from some place else, then do not execute what's below me."
Feel free to follow up below if I misinterpreted your question.
You never do anything with the result of read_strings. Try:
print(read_strings(file1))