I've written a script that only runs on version 2.6 or 2.7. I've placed in a safety check to see if another version is installed and to also check if there are any compatible versions available. Here is my code snippet;
# !/usr/bin/python
import sys, os, re
from sys import exit
if sys.version[0:3] in ['2.6', '2.7']:
import subprocess, datetime, os.path, json, urllib2, socket
def python_version():
version = sys.version[0:3]
while version not in ['2.6', '2.7']:
print '\n\nYou\'re using an incompatible version of Python (%s)' % version
python_installed_version = []
for files in os.listdir("/usr/bin/"): # check to see version of python already on the box
python_version = re.search("(python2(.+?)[6-7]$)", files)
if python_version:
python_installed_version.append(python_version.group())
if python_installed_version:
print 'Fortunately there are compatible version(s) installed. Try the following command(s): \n\n',
for version in python_installed_version:
print 'curl http://script.py | %s\n' % version
sys.exit()
python_version()
with p.stdout:
print 'hello'
When I run the above in python 2.4 I get this error;
File "<stdin>", line 46
with p.stdout:
^
SyntaxError: invalid syntax
I don't understand why the script doesn't exit as soon as it detects that you're using python 2.4 with sys.exit(), but instead carries on reading the script and gives the error above where the with p.stout: is read.
I have removed the with p.stdout: line, and it will work fine, it won't read the print 'hello'. I don't know why the with p.stdout: is causing the script to break. This works perfectly fine on 2.6 and 2.7.
Any ideas on why python 2.4 will still read the with p.stdout: line? Thanks.
Python 2.4 doesn't have the with syntax support yet, so the script fails at the parsing stage, rather than at runtime. You can work around that by having some wrapper like:
if version_check_ok():
import actual_app
actual_app.run()
else:
...
This way the new files with the new syntax will not be imported/parsed until you know it's safe to do so. You can't move the import above the version check however.
Related
When I do pylint main.py, I get the following error:
E: 7, 0: invalid syntax (<string>, line 7) (syntax-error)
# main.py
import os
repo = os.environ.get('GITHUB_REPOSITORY')
branch = os.environ.get('GITHUB_REF')
commit = os.environ.get('GITHUB_SHA')
commit_url = f'https://github.com/{repo}/commit/{commit}'
repo_url = f'https://github.com/{repo}/tree/{branch}'
print(commit_url, repo_url)
The code is running as expected but pylint is giving this strange error. I am using Python 3.6.9 on Ubuntu 18.04.
It looks like PyLint isn't happy with your f-strings (introduced in 3.6) and is validating against the syntax of an older Python version. I'd check whether the PyLint you are using is running from the same Python environment your Python you are running the program with. I would guess it's running from your system Python, while your program is running from a virtual environment.
With pylint 2.5.3 and Python 3.8.2 the only complaint PyLint makes is about the lack of a module docstring.
************* Module main
main.py:1:0: C0114: Missing module docstring (missing-module-docstring)
-----------------------------------
Your code has been rated at 8.57/10
Use .format method like below
import os
repo = os.environ.get('GITHUB_REPOSITORY')
branch = os.environ.get('GITHUB_REF')
commit = os.environ.get('GITHUB_SHA')
commit_url = 'https://github.com/{}/commit/{}'.format(repo, commit)
repo_url = 'https://github.com/{}/tree/{}'.format(repo, branch)
print(commit_url, repo_url)
Check here, Python 3 returns "invalid syntax" when trying to perform string interpolation
I need some advice with a Python script. I'm still new and learned it by myself. I found the script on Google. After I retype it, it doesn't print the result in the console. How can the result of the script be shown in the console? Details as below:
C:\Python27>test1.py af8978b1797b72acfff9595a5a2a373ec3d9106d
C:\Python27>
After I press enter, nothing happens. Should the result be shown or not?
Here's the code that I retyped:
#!/usr/bin/python
#coding: ascii
import requests
import sys
import re
url = 'http://hashtoolkit.com/reverse-hash?hash='
try:
hash = sys.argv[1]
except:
print ("usage: python "+sys.argv[0]+" hash")
sys.exit()
http = request.get(url+hash)
content = http.content
cracked = re.findall("<span title=\*decrypted (md5|sha1|sha384|sha512) hash\*>(.*)</span>", content) # expression regular
print ("\n\tAlgoritmo: "+cracked[0][0])
print ("\tPassword Cracked: "+cracked[0][1])
The first line in your script is called a Shebang line.
A Shebang line tells the script to run the Python interpreter from that location.
The shebang line you provided is a Linux system path, but it looks from the path you are executing Python from, that you are running on Windows.
You can do one of two things here to fix that:
Remove the Shebange Line.
Remove the first line from your script.
Execute the script using python test1.py COMMAND_LINE_ARGUMENTS
Modify Your Shebang line.
Change the first line of your script from !/usr/bin/python to
#!python (This is assuming that python is in your systems PATH variable.)`
Execute the script using test1.py COMMAND_LINE_ARGUMENTS
Also, you are trying to import the requests module that is not installed in the standard library.
If you haven't installed this yet, you can do so by going to your Python install directory and go to the scripts folder.
Hold shift and right click and go Open command window here
Type pip install requests and hit enter.
After that you should be good to go, execute the script by navigating to it and type test.py COMMAND_LINE_ARGUMENT
If a Python script doesn't have the shebang line:
python test.py COMMAND_LINE_ARGUMENT
you need to run your script using python. try:
C:\Python27>python test1.py af8978b1797b72acfff9595a5a2a373ec3d9106d
I have just started learning Hadoop. I tried to run a simple mapreduce job on it, but before that I tried to check it locally. But its returning error. Kindly suggest any solution to it. I am using Ubuntu 12.04 LTS.
SO the code is written in gedit, and is ad follows.
import sys
for line in sys.stdin:
line = line.strip()
words = line.split()
for word in words:
print '%s\t%s' %(word,1)
Then I write the below command in terminal to check if mapper is working fine
maitreyee#bharti-desktop:~$ echo "foo faa" | /home/maitreyee/Documents/mapper.py
and the terminal returns the following error:
/home/maitreyee/Documents/mapper.py: line 1: import: command not found
/home/maitreyee/Documents/mapper.py: line 5: syntax error near unexpected token `line'
/home/maitreyee/Documents/mapper.py: line 5: `line = line.strip()'
You are missing the shebang line at the top of your script. Add something like this (whichever python makes sense for your machine):
#!/usr/bin/python
Here I use the system python under /usr/bin/python
The shebang line is needed because you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH.
If you want more to know about writing map reduce code in python, you can follow this
tutorial!
Python is seeing some problem with how I am opening a file with the code below
if __name__ == "__main__":
fileName = sys.argv[1]
with open(fileName, 'r') as f:
for line in f:
print line
It is producing the error
./search.py: line 3: syntax error near unexpected token `('
./search.py: line 3: ` with open(fileName, 'r') as f:'
Am I missing an import? What could be the cause of this?
EDIT: OS - CentOS, Python version 2.6.6
Not sure how I installed, I am running an image from a .edu openstack site. Not sure of the distribution, binaries, ...
You must add import sys in order to use sys.argv. Check this out.
I have tried this:
chmod u+x yourfile.py
./yourfile.py
and it gives me:
./jd.py: line 4: syntax error near unexpected token `('
./jd.py: line 4: ` with open(fileName, 'r') as f:'
If you are doing ./search.py file then add at the beginnig of your file #!/usr/bin/env python. Otherwise, use python file.py input
The problem is that you aren't running your program with Python at all! When you do ./script (assuming that script is a text script, and not a binary program), the system will look for a line at the top of the file beginning with the sequence #!. If it finds that line, the rest of the line will be used as the interpreter of that script: the program which runs the script. If it doesn't find that line, the system defaults to /bin/sh.
So, basically, by omitting the magic line #!/usr/bin/python at the top of your script, the system will run your Python script using sh, which will produce all sorts of incorrect results.
The solution, then, is to add the line #!/usr/bin/python (or an equivalent line, like #!/usr/bin/env python) to the top of your Python script so that your system will run it using Python. Alternately, you can also always run your program using python search.py, instead of using ./search.py.
(Note that, on Linux, filename extensions like .py mean almost nothing to the system. Thus, even though it ends with .py, Linux will just execute it as if you wrote /bin/sh search.py).
Either:
the first line of search.py should be a #! comment specifying the path to locate the python executable, usually [#!/usr/bin/env python](Why do people write #!/usr/bin/env python on the first line of a Python script?
on-the-first-line-of-a-python-script). Usually this is #!/usr/env/bin python . Don't use a hardpath e.g. #/opt/local/bin/python2.7
or else you can invoke as python yourfile.py <yourargs> ...
PREVIOUS: If import sys fails, post more of your file please.
Maybe your install is messed up.
Can you import anything else successfully, e.g. import re?
What are your platform, OS and Python version? How did you install? source? binaries? distribution? which ones, from where?
I have a software that has python 2.5.5. I want to send a command that would start a script in python 2.7.5 and then proceed with the script.
I tried using
#!python2.7.5
and http://redsymbol.net/articles/env-and-python-scripts-version/
But I cant get it to work...
In my python 2.5.5 I can execute script as
execfile("c:/script/test.py")
The problem is that the 2.7.5 has a module comtypes + few other. I dont know how to install it for my 2.5.5 so I'm trying to start a separate script and run it under python27. Now another reason why I want it its because I want to take the load off program. I have 2 heavy tasks to perform. The second task is the one that need comptypes so sending it to external shell/app would do perfect trick. Is there a way to do it ?
I wish I could just type run("C:/Python27/python.exe % C:/script/test,py")
Thanks, bye.
Little update. I try to run
import os
os.system("\"C:\Python27\python.exe\" D:\test\runTest.py")
But I'm getting a quick pop up and close window saying that
Import Error : no module named site...
This works if I run from external shell but not from here :(
So I've tried another approach this time to add modules to python... in any case I run this :
import os
import sys
sys.path.append("C:/python27")
sys.path.append("C:/Python27/libs")
sys.path.append("C:/Python27/Lib")
sys.path.append("C:/Python27/Lib/logging")
sys.path.append("C:/Python27/Lib/site-packages")
sys.path.append("C:/Python27/Lib/ctypes")
sys.path.append("C:/Python27/DLLs")
import PyQt4
print PyQt4
import comtypes
import logging
but it crashes with C error...
Runtime Error :
Program: c:\Pr...
R6034
An application has made attempt to load the C runtime library incorectly.
blablabla....
How can I import it ? Maybe if I can import it I can run it directly from my app rather than starting separate python...
Traceback (most recent call last):
File "<string>", line 18, in <module>
File "C:\Python27\Lib\site-packages\comtypes\__init__.py", line 22, in <module>
from ctypes import *
File "C:\Python27\Lib\ctypes\__init__.py", line 10, in <module>
from _ctypes import Union, Structure, Array
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.
Another update to isseu
so I run now
import os
os.system("start cmd {D:\test\runTest.py}")
now this works and he open CMD with c:\Python27 as directory but he dont run the file... any hitns how to fix it?
Use "raw" strings so that you don't need to escape as much; I think the backslashes are what was breaking your code since backslash is considered an escape character except in raw strings.
Also, use the subprocess module. It makes it easy to avoid manually making a safe command string (the module takes care of that for you). All you need to do is pass it a list of arguments.
Your code would then look something like this:
import subprocess
proc = subprocess.Popen([r"C:\Python27\python.exe", r"D:\test\runTest.py"])
# then either do this
proc.wait() # wait until the process finishes
# or this
while True:
# NOTE: do something else here
# poll the process until it is done
if proc.poll() is not None:
break # break out of loop
See subprocess docs for Python 2 here. Be sure to check if a feature was added after Python 2.5 (the 2.5 docs aren't available online anymore AFAIK).
UPDATE:
I just noticed that you tried to use the Python 2.7 libraries and modules in your 2.5 code. This probably won't work due to new features added after 2.5. But it got me thinking how you might be able to make 2.7 work.
It may be that your Python2.7 install can't find its libraries; this is probably why you get the error Import Error : no module named site. You can do something like the above and modify the PYTHONPATH environment variable before starting the subprocess, like this:
import os
import subprocess
paths = [r"C:\python27", r"C:\python27\libs", r"C:\python27\Lib\site-packages", r"C:\python27\DLLs"]
paths += os.environ.get('PYTHONPATH', '').split(os.pathsep)
env27 = dict(os.environ)
env27['PYTHONPATH'] = os.pathsep.join(paths)
proc = subprocess.Popen([r"C:\Python27\python.exe", r"D:\test\runTest.py"], env=env27)