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
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
>>>
OK so for school I am having to set up a computer using Ubuntu 12.04 to run Python programs written in Python 3.3. I was aware that 12.04 came with Python 3.2, so I followed the procedure in the first reply in this thread to install Python 3.3:
Now when I open the Terminal, I type ~/bin/py to get it to display the following at the top of the terminal:
Python 3.3.2 (default, Dec 10 2013, 11:35:01)
[GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
>>>
So far so good. Now I am having trouble replicating the functionality of the same Python program that I execute as follows on my Windows laptop.
(This is what I type in the Python commandline on windows)
import filereader
from filereader import *
reader = filereader("C:\Python33\ab1copy.ab1")
reader.show_entries()
The end result is a directory of data types found in the file. The filereader class is located in Python33\Lib\site-packages\filereader.py in the above example. On the Ubuntu computer its location is Python-3.3.2\Lib\site-packages\filereader.py. Also on Ubuntu, the ab1copy.ab1 file is located in the home directory for now.
After I achieve the recognition of Python 3.3.2 in the Ubuntu Terminal as noted above, how can I replicate my program's functionality there? If I try to put in the same first command "import filereader" I get the following error:
>>>import filereader
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'filereader'
try this in the terminal
python3 your_file.py
It's probably not in your python path.
Check this to see where it looks for your source:
import sys
print(sys.path)
I have some lines of python code that I'm continuously copying/pasting into the python console. Is there a load command or something I can run? e.g. load file.py
From the man page:
-i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.
So this should do what you want:
python -i file.py
For Python 2 give execfile a try. (See other answers for Python 3)
execfile('file.py')
Example usage:
Let's use "copy con" to quickly create a small script file...
C:\junk>copy con execfile_example.py
a = [9, 42, 888]
b = len(a)
^Z
1 file(s) copied.
...and then let's load this script like so:
C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('execfile_example.py')
>>> a
[9, 42, 888]
>>> b
3
>>>
Python 3: new exec (execfile dropped) !
The execfile solution is valid only for Python 2. Python 3 dropped the execfile function - and promoted the exec statement to a builtin universal function. As the comment in Python 3.0's changelog and Hi-Angels comment suggest:
use
exec(open(<filename.py>).read())
instead of
execfile(<filename.py>)
From the shell command line:
python file.py
From the Python command line
import file
or
from file import *
You can just use an import statement:
from file import *
So, for example, if you had a file named my_script.py you'd load it like so:
from my_script import *
Open command prompt in the folder in which you files to be imported are present. when you type 'python', python terminal will be opened. Now you can use import script_name Note: no .py extension to be used while importing. How can I open a cmd window in a specific location?
If you're using IPython, you can simply run:
%load path/to/your/file.py
See http://ipython.org/ipython-doc/rel-1.1.0/interactive/tutorial.html
If your path environment variable contains Python (eg. C:\Python27\) you can run your py file simply from Windows command line (cmd).
Howto here.