I am learn python now, and today, i met a problem
in
http://docs.python.org/release/2.5.4/tut/node8.html
6.1.1 Executing modules as scripts
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the
__name__ set to "__main__". That means that by adding this code at the end of
your module:
if __name__ == "__main__":
import sys`
fib(int(sys.argv[1]))
you can make the file usable as a script as well as
an importable module, because the code
that parses the command line only runs
if the module is executed as the
"main" file:
$ python fibo.py 50 1 1 2 3 5 8 13 21
34
but when i do this in shell, i got
File "<input>", line 1
python fibo.py 222
SyntaxError: invalid syntax
how to execute script correctly?
fibo.py is
def fib(n):
a,b=0,1
while b<n:
print b,
a,b = b,a+b
def fib2(n):
result=[]
a,b=0,1
while b<n:
result.append(b)
a,b=b,a+b
return result
if __name__ =="__main__":
import sys
fib(int(sys.argv[1]))
What exactly did you do in the shell? What is the code you are running?
It sounds like you made a mistake in your script - perhaps missing the colon or getting the indentation wrong. Without seeing the file you are running it is impossible to say more.
edit:
I have figured out what is going wrong. You are trying to run python fibo.py 222 in the python shell. I get the same error when I do that:
[138] % python
Python 2.6.1 (r261:67515, Apr 9 2009, 17:53:24)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> python fibo.py 222
File "<stdin>", line 1
python fibo.py 222
^
SyntaxError: invalid syntax
>>>
You need to run it from the operating system's command line prompt NOT from within Python's interactive shell.
Make sure to change to Python home directory first. For example, from the Operating system's command line, type: cd C:\Python33\ -- depending on your python version. Mine is 3.3. And then type: python fibo.py 200 (for example)
Related
I'm a beginner in Python. I tried to resolve this error but I couldn't. This code worked before but not anymore. I run the code in PyCharm and getting this error:
Traceback (most recent call last):
File "C:/Users/MJavad/Desktop/test.py", line 3, in <module>
b = float(sys.argv[1])
IndexError: list index out of range
I ran CMD and had also an error:
File "<stdin>", line 1
python test.py 1 2
^
SyntaxError: invalid syntax
Can anyone help, please? This is my code:
import sys
import math
b = float(sys.argv[1])
c = float(sys.argv[2])
f = b * b - 4.0 * c
d = math.sqrt(f)
print((-b + d) / 2.0)
print((-b - d) / 2.0)
and this is the code and error in PyCharm:
It seems that there is confusion about how Python code can be executed and processed.
On the one hand, there is the Python interpreter in the interactive mode. This is usually started with the command python (without arguments) and then you have the possibility to execute Python code directly in an interactive Python specific shell. This distinguishes Python from other languages that need to be compiled first to execute code. Further information are available in the official Python tutorial.
On the other hand, Python can also be executed in such a way that not the interpreter with an interactive shell is started, but a file is read and processed. This is usually done with the command python together with the path to the Python file as argument, e.g. python test.py. See also the documentation about using Python.
With this knowledge the problems that have happened to you can now be explained and solved:
If you are simply starting the Python interpreter in interactive mode (without any further arguments), you don't have access to the command line arguments any more, for example:
$ python3.8 # or whatever your command is, maybe only python or python3
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys; sys.argv
['']
As you can see, there isn't really a usable information in argv. And that is your problem: The arguments aren't successfully loaded into sys.argv. So an index error happened, because the arguments are simply missing:
$ python3.8
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
The only difference to your example is that you have already provided the path to the script, because it's File "C:/Users/MJavad/Desktop/test.py", line 3, in <module> instead of File "<stdin>", line 1, in <module>. So you have started the program via python test.py, but also without any further arguments which would be loaded into sys.argv in the program, see:
$ python3.8 test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
b = float(sys.argv[1])
IndexError: list index out of range
Your sys.argv now looks like this: ['test.py'], but still no index positions 1 and 2 available. So you have to invoke python also with additional arguments which will be passed into sys.argv:
$ python3.8 test.py 1 2
Traceback (most recent call last):
File "test.py", line 6, in <module>
d = math.sqrt(f)
ValueError: math domain error
And it worked! Ok, you have another exception, but it's in line 6 and every line before was successfully processed, also the command line arguments. Now you can proceed to debug your program, i.e. start programming or trying other parameters than 1 and 2 etc.
So that's the theory. Since you're also using PyCharm and have the "Terminal", the "Run configuration" and a "Python Console" available, things get a bit more complicated:
The "Terminal" should have a prompt available if you start one. This prompt shouldn't be a prompt from the Python interpreter (normally prefixed by >>>). It should be a terminal prompt (normally prefixed by an $ at the end), where you can also start a python interpreter in interactive mode or start a python program as described above. This "Terminal" is a terminal emulator given you by PyCharm and can also do other things for you, not only starting python programs. See the PyCharm documentation for more information.
The "Python Console" is a similar Python interpreter you also can get if starting python from the "Terminal". But then, you already started the interactive mode of the interpreter and there are no possibilities to pass command line arguments (maybe somewhere, but not as default). See the PyCharm documentation for more information.
If you're using an IDE like PyCharm, you should normally start the program as recommended by the IDE. In this case, you're writing a file and start the file neither by running the "Terminal", nor going into an interactive Python shell. Instead of this, you have to configure the IDE "Run" as described in the PyCharm documentation or as you can see here:
This is just the GUI way of calling python C:/Users/MJavad/Desktop/test.py 1 2 directly inside PyCharm.
So I would recommend that you're only starting your programs via option 3 (via "Run" configuration or "DEBUG" configuration). You only have to pay attention, running the right configuration (see if the path is the correct one and the parameters are right).
It is not normal to have a Python prompt (>>>) directly after starting a "Terminal", though. And inside interactive mode of Python's interpreter, you simply cannot start a python script, because you're already in a python interpreter, for example:
$ python3.8
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> python test.py 1 2
File "<stdin>", line 1
python test.py 1 2
^
SyntaxError: invalid syntax
I should also mention that you can pass arguments into python interactive mode, for example (the - stands for <stdin>):
$ python3.8 - hello world
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys; sys.argv
['-', 'hello', 'world']
>>>
Actually I found the solution of my main problem "Get the full path to the directory a Python file is contained in" from the previous answer : Find current directory and file's directory.
And the code below from the answer works well if I run my entire script, in other words, hotkey F5.
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
However, if I just select the two lines of the above code and run it, in other words, hotkey F9. Then I will receive the error below:
NameError: name '__file__' is not defined
So if anyone happens to know why the error occurs, please give a brief explanation.
Thanks a lot!
By the way, i used Spyder (Python 2.7).
Inside Spyder or any interactive python process, the constant __file__ is not defined.
When you run the whole script, Spyder basically run the following command:
$ python script.py
While, if you select those two lines, it's more like entering a interactive python process first, then interpret the statements:
$ python
Python 2.7.13 (default, Jun 12 2017, 17:25:44)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> dir_path = os.path.dirname(os.path.realpath(__file__))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
>>>
That's the difference.
My default Python binary is set to the one with the Anaconda distribution of Python. This is found at /home/karnivaurus/anaconda/bin/python, and I have made this the default by adding to my .bashrc file the following: export PATH=/home/karnivaurus/anaconda/bin:$PATH.
I also have a Python package called caffe, which is located at /home/karnivaurus/caffe/distribute/python, and I have added this to the package search path by adding to my .bashrc file the following: export PYTHONPATH=${PYTHONPATH}:/home/karnivaurus/caffe/distribute/python.
Now, I have a simple Python file, called test.py, with the following contents:
import caffe
print "Done."
If I run this by entering python test.py into the terminal, it runs fine, printing out "Done.". The problem I am having is when I run this in the PyCharm IDE. In PyCharm, I have set the interpreter to be /home/karnivaurus/anaconda/bin/python. But when I open test.py in PyCharm, and run the file in the IDE, I get the following error:
ImportError: No module named caffe
So my question is: Why can PyCharm not find the caffe module when it runs the Python script, but it can be found when I run the script from the terminal?
There are a few things that can cause this. To debug, please modify your test.py like so:
# Is it the same python interpreter?
import sys
print(sys.executable)
# Is it the same working directory?
import os
print(os.getcwd())
# Are there any discrepancies in sys.path?
# this is the list python searches, sequentially, for import locations
# some environment variables can fcuk with this list
print(sys.path)
import caffe
print "Done."
Try again in both situations to find the discrepancy in the runtime environment.
edit: there was a discrepancy in sys.path caused by PYTHONPATH environment variable. This was set in the shell via .bashrc file, but not set in PyCharm's runtime environment configuration.
For an additional option, you can use pycharm by terminal. And export the corresponding environment paths beforehand. This works for me. And I think it's better than make some changes in the code. You gonna need run the code by terminal after your debugging.
For example, in terminal type:
$ export LD_LIBRARY_PATH=~/build_master_release/lib:/usr/local/cudnn/v5/lib64:~/anaconda2/lib:$LD_LIBRARY_PATH
$ export PYTHONPATH=~/build_master_release/python:$PYTHONPATH
Then run pycharm by charm (pycharm can be soft linked by charm bash):
$ charm
Well this may be a redundant answer, however I think it's important to explicitly called out what causes this error.
It happened to me many times and I got it fixed by making sure that IDE ( pycharm or vscode or any other) is set to same working directory where the code resided.
for example : I have two files train.py and config.py in mlproject/src directory. I'm trying to run import config in train.py
**When run in /mlproject/ directory, I get error when try to import config **
(ml) dude#vscode101:~/mlproject$ python
Python 3.7.6 (default, Jan 8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import config
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'config'
>>>
When run in /mlproject/src/` directory, I'm able to successfully import config
(ml) dude#vscode101:~/mlproject/src$ python
Python 3.7.6 (default, Jan 8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import config
>>>
I am getting the following errors when trying to run a piece of python code:
import: unable to open X server `' # error/import.c/ImportImageCommand/366.
from: can't read /var/mail/datetime
./mixcloud.py: line 3: syntax error near unexpected token `('
./mixcloud.py: line 3: `now = datetime.now()'
The code:
import requests
from datetime import datetime,date,timedelta
now = datetime.now()
I really lack to see a problem. Is this something that my server is just having a problem with and not the code itself?
those are errors from your command shell. you are running code through the shell, not python.
try from a python interpreter ;)
$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> from datetime import datetime,date,timedelta
>>>
>>> now = datetime.now()
>>>
if you are using a script, you may invoke directly with python:
$ python mixcloud.py
otherwise, ensure it starts with the proper shebang line:
#!/usr/bin/env python
... and then you can invoke it by name alone (assuming it is marked as executable):
$ ./mixcloud.py
Check whether your #! line is in the first line of your python file. I got this error because I put this line into the second line of the file.
you can add the following line in the top of your python script
#!/usr/bin/env python3
I got this error when I tried to run my python script on docker with docker run.
Make sure in this case that you set the entry point is set correctly:
--entrypoint /usr/bin/python
Help! i am getting this error again and again....on light table while i m trying to run python code
File "C:\Python34\Lib\site.py", line 176
file=sys.stderr)
^
SyntaxError: invalid syntax
This is a code with installation.
I have no idea about the Light Table part, but the error you show is the one that you'd get if you were to somehow try to execute a Python 3 print function call under Python 2 (where print is a statement with a quirky syntax rather than a function). Lines 175-176 of site.py in the Python 3.4 distribution look like this (modulo leading indentation):
print("Error processing line {:d} of {}:\n".format(n+1, fullname),
file=sys.stderr)
and sure enough, if you try to execute that in a Python 2 interpreter you'll get a SyntaxError, with the cursor pointing to that same = sign:
Python 2.7.8 (default, Jul 3 2014, 06:13:58)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Error processing line {:d} of {}:\n".format(n+1, fullname), file=sys.stderr)
File "<stdin>", line 1
print("Error processing line {:d} of {}:\n".format(n+1, fullname), file=sys.stderr)
^
SyntaxError: invalid syntax
I'd suggest looking closely at the settings for the Light Table Python plugin to see if anything's awry. You should also check the setting for your PYTHONPATH environment variable. If it includes a reference to the C:\Python34 directory and you're running Python 2, that could be the cause of the problem. Here's an example of the exact same problem on OS X, caused by starting Python 2 with a PYTHONPATH that refers to Python 3's library directory:
noether:~ mdickinson$ export PYTHONPATH=/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/
noether:~ mdickinson$ python2.7
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site.py", line 176
file=sys.stderr)
^
SyntaxError: invalid syntax