Am trying to run the following python program
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
f=open('out.txt')
for a in f:
print regex.findall(a)
print '\n'
when I type the code into the interpreter manually, it works as expected
but when i save it as a file and try to run it , it gives errors.
The command i used to run it is
chmod +x
sudo ./pymod.py
ERROR:
./pymod.py: 2: Syntax error: "(" unexpected
if i dont use sudo, the error i get is
./pymod.py: line 2: syntax error near unexpected token `('
./pymod.py: line 2: `regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")'
am using ubuntu 10.04 with everything on default
it takes about 10-15 seconds for the error to appear
Your file should start with shebang. You should include the path to the python interpreter
#!/usr/bin/env python
import re
regex=re.compile("http...imgs.xkcd.com.comics.[\\S]*.[jpg|png]")
Check out : http://en.wikipedia.org/wiki/Shebang_(Unix)
This is probably executing as a bash script instead of in Python. Put
#!/usr/bin/env python
at the beginning of your script.
When you set something as executable, you have to specify what you want it to run it with, or Linux will consider it to be a bash script.
Add this as the first line of the file:
#!/usr/bin/python
Or run it like:
python pymod.py
Cheers!
Either use the "shebang". I.e. put
#! /usr/bin/python
as the first line of your script.
Or teach your ubuntu how to treat python scripts without it
as described here: http://www.daniweb.com/code/snippet241988.html
Related
Well I have this code:
#!/usr/bin/env python3
for i in range(15):
print(i, end=' ')
when I run it like this in command prompt:
prog1.py
I get:
C:\Users\Ja\Desktop>prog1.py
File "C:\Users\Ja\Desktop\prog1.py", line 4
print(i, end=' ')
^
SyntaxError: invalid syntax
but when I run it like this:
py prog1.py
it works fine. It's running python2.7.15 instead of python3.6.5 (I tested it using sys.version).
( It's the same for icon clicks )
You may be under the impression that Windows understands the "shebang line":
#!/usr/bin/env python3
It does not. All Windows knows is that .py files can be run by Python. So you need to update your file association, or run the correct version of Python explicitly, passing the path to your script as an argument.
I have a bash script which changes the path on my command line,
This one,
#!/usr/bin/env python
cd /mnt/vvc/username/deployment/
I have a python script which i wish to run after the path changes to the desired path,
The script,
#!/usr/bin/env python
import subprocess
import os
subprocess.call(['/home/username/new_file.sh'])
for folder in os.listdir(''):
print ('deploy_predict'+' '+folder)
I get this
File "/home/username/new_file.sh", line 2
cd /mnt/vvc/username/deployment/
^
SyntaxError: invalid syntax
Any suggestions on how can i fix this?thanks in advance
You need to explicitly tell subprocess which shell to run the sh file with. Probably one of the following:
subprocess.call(['sh', '/home/username/new_file.sh'])
subprocess.call(['bash', '/home/username/new_file.sh'])
However, this will not change the python program's working directory as the command is run in a separate context.
You want to do this to change the python program's working directory as it runs:
os.chdir('/mnt/vvc/username/deployment/')
But that's not really great practice. Probably better to just pass the path into os.listdir, and not change working directories:
os.listdir('/mnt/vvc/username/deployment/')
When I manually run this command in Terminal, it executes, but through Python it gives the error that the directory is not available in Python packages.
I am using the following command
source ~/trytry/shell.sh
This is my test shell file:
#!/bin/sh
echo hello
when I executed " source ~/test.sh ", it will print hello at console.
This is my python code:
>>> import commands
>>> commands.getstatusoutput("source ~/test.sh")
(0, 'hello')
It works without any problem. So, would you please show your code?
What it looks like to me is that you have a shell script, and not a python file which would have the .py extension instead of .sh. The error may have to do with the fact that it isn't a python file you're trying to run.
I am trying to use this Python urllib2 Basic Auth Problem bit of code to download a webpage content from an URL which requires authentication. The code I am trying is:
import urllib2, base64
request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
result = urllib2.urlopen(request)
It's showing me:
./xx.py: line 1: import: command not found
./xx.py: line 3: syntax error near unexpected token `('
./xx.py: line 3: `request = urllib2.Request("http://api.foursquare.com/v1/user")'
I am wondering what I am doing wrong? I am using Python 2.7.5. How can I download file contents from an URL which requires authentication?
It's not an issue related to authentication at the first step. Your import is not working. So, try writing this on first line:
#!/usr/bin/python
and for the time being run using
python xx.py
For you here is one explanation:
>>> abc = "Hei Buddy"
>>> print "%s" %abc
Hei Buddy
>>>
>>> print "%s" %xyz
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print "%s" %xyz
NameError: name 'xyz' is not defined
At first, I initialized abc variable and it works fine. On the otherhand, xyz doesn't work as it is not initialized!
When you see "import: command not found" on the very first import, it is caused by the parser not using the character encoding matching your py file. Especially when you are not using ASCII encoding in your py file.
The way to get it right is to specify the correct encoding on top of your py file to match your file character encoding.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
Are you using a UNIX based OS such as Linux? If so, add a shebang line to the very top of your script:
#!/usr/bin/python
Underneath which you would have the rest of the code (xx.py in your case) that you already have. Then run that same command at the terminal:
$ python xx.py
This should then work fine, as it is now interpreting this as Python code. However when running from the terminal this does not matter as python tells how to interpret it here. What it does allow you to do is execute it outside the terminal, i.e. executing it from a file browser.
If you run a script directly e.g., ./xx.py and your script has no shebang such as #!/usr/bin/env python at the very top then your shell may execute it as a shell script. POSIX says:
If the execl() function fails due to an error equivalent to the
[ENOEXEC] error defined in the System Interfaces volume of
POSIX.1-2008, the shell shall execute a command equivalent to having a
shell invoked with the pathname resulting from the search as its first
operand, with any remaining arguments passed to the new shell, except
that the value of "$0" in the new shell may be set to the command
name. If the executable file is not a text file, the shell may bypass
this command execution. In this case, it shall write an error message,
and shall return an exit status of 126.
Note: you may get ENOEXEC if your text file has no shebang.
Without the shebang, you shell tries to run your Python script as a shell script that leads to the error: import: command not found.
Also, if you run your script as python xx.py then you do not need the shebang. You don't even need it to be executable (+x). Your script is interpreted by python in this case.
On Windows, shebang is not used unless pylauncher is installed. It is included in Python 3.3+.
I've experienced the same problem and now I just found my solution to this issue.
#!/usr/bin/python
import sys
import os
os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))
This is the code[1] for my case. When I tried this script I received error message like :
import: command not found
I found people talks about the shebang. As you see there is the shebang in my python code above.
I tried these and those trials but didn't find a good solution.
I finally tried to type the shebang my self.
#!/usr/bin/python
and removed the copied one.
And my problem solved!!!
I copied the code from the internet[1].
And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.
I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)
Journeyer
PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.
[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy
It's about Shebang
#!usr/bin/python
This will tell which interpreter to wake up to run the code written in file.
I want to run a python script without explicitly having to call "python" every time in my shell. I've tried to add the shebang #!/path/to/python but this does not seem to work. Does anyone know a work around this? Many thanks.
You've got to add the shebang:
#!/usr/bin/env python
Then make the script executable:
chmod +x foo
Then you can run it like any other executable:
./foo
And a note from Homer6: if you're editing the file from windows and invoking it on linux, you may run into the cryptic "No such file or directory" error. It's due to the line endings of the lines being CRLF instead of LF. If you convert them to LF, the script will execute as expected. Notepad++ > View > Show Symbols > Show End of Line to show the EOL characters. And Notepad++ > Edit > EOL Conversion > Unix Format to convert all line endings to use LF. Alternatively, you can use the dos2unix tool (dos2unix foo.py), which is present on most Linux systems.
It didn't really apply to your personal scripts but as you are quoting beets, note that it is also possible to automate this action when you are distributing your packages, thanks to setuptools entry_point option.
So if you are distributing a package like myModule and want to make the main_function() function accessible via typing mymodulescript in the console you would probably add something like this to your setup.py file :
setup(
# your other arguments ..
entry_points={
'console_scripts': [
'mymodulescript = myModule:main_function'
]
}
)
Add a line at the top of your script:
#! /usr/bin/env python
Rename your script from script_name.py to script_name
make the script executable: chmod +x script_name
The line at the top selects the same python that you get when typing python at the prompt. You can also specify a direct path:
#!/opt/python/3.6/bin/python
Another workaround could be to use an alias defined in the .bashrc :
e.g. add the following line in your .bachrc file :
alias mypythonalias="python mypyrhonfile.py"
type in terminal :
source ~/.bashrc
and then you may simply type:
mypythonalias
to execute the python file.
Ensure you are able to run /path/to/python on your terminal. And make sure you have given execute permission for your python file. You can give permission for the file by
chmod +x mypythonfile.py