ModuleNotFoundError: No module named 'pyzabbix' - python

pyzabbix is a module needed for this script to work. I installed it using pip, please see a confirmation below:
WARNING: The script chardetect.exe is installed in 'C:\Users\Christopher Ezimoha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed certifi-2019.11.28 chardet-3.0.4 idna-2.8 pyzabbix-0.7.5 requests-2.22.0 urllib3-1.25.8
C:\Users\Christopher Ezimoha\Desktop>
However, I'm getting an error at line 24 that the module can't be found. I'm not sure what I need to do.
Please see the script below and advise accordingly as I need this code to read a CSV file and update an application called Zabbix.
def addHosts(zapi):
# Add Hosts
file = open('hosts.csv', 'r')
reader = csv.reader(file)
devicelist = list(reader)
import csv
def login():
# Login/authenticate below
session = ZabbixAPI('https://zabbix.xxxxxx.xxx')
# session = ZabbixAPI('http://xxxxxxxxxx/zabbix')
session.login(user="xxxxxxxxxxxx", password="xxxxxxxx")
print("Connected to Zabbix API Version %s" % session.api_version())
return session
for row in devicelist:
device = row[0]
hostgroup = row[1]
responsegroup = zapi.hostgroup.get(filter={'name': hostgroup})
groupid = responsegroup[0]['groupid']
ip = row[2]
templatePriority = row[3]
responsepriority = zapi.template.get(filter={'name': templatePriority})
templatePriorityId = responsepriority[0]['templateid']
# if templatePriority == 'P1':
# templatePriorityId = '40874'
templateType = row[4]
responsetype = zapi.template.get(filter={'name': templateType})
templateTypeId = responsetype[0]['templateid']
try:
response = zapi.host.create(
host=device,
interfaces=[{
'type': 2,
'main': 1,
'ip': ip,
'dns': '',
'port': 161,
'useip': 1
}],
groups=[{
'groupid': groupid}],
templates=[{'templateid': templatePriorityId}, {'templateid': templateTypeId}],
inventory_mode=1
)
print("Created new host: " + device)
except ZabbixAPIException as e:
if 'already exists' in e[0]:
print("Already created host " + device)
else:
print(e[0])
return
def main():
# hostgroup = raw_input('Hostgroup: ')
#hostgroup = "ALTC - Altcar"
zapi = login()
addHosts(zapi)
return
if __name__ == '__main__':
main()

Do you have both python 2 and 3 installed? If you have both, pip installs modules under python2. Try installing like this if you'd like the module to be installed under python3:
pip3 install pyzabbix

There is no import, in the code you included in the question:
from pyzabbix import ZabbixAPI
The login() function should be defined outside of addHosts(), in order to be called like that in main()

Related

Import requests ModuleNotFoundError: No module named 'requests'

I need to run this code but I find this error:
Traceback (most recent call last):
File "C:\Users\DELL\Downloads\snapArt.py", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
Code:
import requests
from hashlib import sha256
from time import time, sleep
print("""
""")
FielUser = open('Users.txt' , 'r').read().splitlines()
req = requests.session()
def token():
for i, c in enumerate("0001110111101110001111010101111011010001001110011000110001000110"):
if c == "0":
yield sha256(("iEk21fuwZApXlz93750dmW22pw389dPwOk"+"m198sOkJEn37DjqZ32lpRu76xmw288xSQ9").encode('utf-8')).hexdigest()[i]
else:
yield sha256((str(int(round(time() * 1000.0))) + "iEk21fuwZApXlz93750dmW22pw389dPwOk").encode('utf-8')).hexdigest()[i]
for user in FielUser:
if user:
user = user.strip()
url = 'https://app.snapchat.com/loq/suggest_username_v2'
headers = {'User-Agent':'Snapchat/10.25.0.0 (Agile_Client_Error; Android 5.1.1#500181103#22; gzip)'}
data = {
'req_token': "".join(list(token())),
'requested_username': user,
'timestamp': int(round(time() * 1000.0)),
'status_code': ''
}
res = req.post(url, headers=headers, data=data)
if res:
JSON = res.json()
#print(JSON)
if JSON.get('requested_username') and JSON.get('status_code') == 'OK':
with open('Found.txt', "a+") as file_save:
file_save.write(user + '\n')
print('available ->', user)
sleep(1)
else:
print('not available ->', user)
sleep(1)
print('''
''')
Be sure you are not in a virtual environment (venv). This could be one of your issues.
You would not have installed the module called requests. To do that simply open your cmd (command prompt) or terminal and type pip install requests.

Multiprocessing with Django when importing a external module

I built a scraping module "scraper.py" that also has the ability to download file and I imported this module into django views. Issue is that in the scraper.py, this " __name__='__main__" is included where the multiprocessing pool is, so when I import the module and try to run it, it doesn't work because it isn't the main.
This is the script(scraper.py) that uses the pool method.
def download(self, url):
response = self._is_downloadable(url)
if response:
name = response.headers.get('content-disposition')
fname = re.findall('filename=(.+)', name)
if len(fname) != 0:
filename = fname[0]
filename = filename.replace("\"", "")
print(filename)
else :
filename = "Lecture note"
with open(filename, 'wb') as files:
for chunk in response.iter_content(100000):
files.write(chunk)
def download_course_file(self, course):
username = self._login_data["username"]
p = Path(f"{username}-{course}.txt").exists()
if not p:
self.get_download_links(course)
statime = time.time()
if __name__ == "__main__":
with Pool() as p:
with open(f"{username}-{course}.txt", "r") as course_link:
data = course_link.read().splitlines(False)[::2]
p.map(self.download, data)
print(data)
print(f"Process done {time.time()-statime}")
This module is imported in the views and then ran as
import scraper
def download_course(request, id):
course = course = get_object_or_404(Course, id=id)
course_name = (course.course_name)[:6]
person, error = create_session(request)
if "invalid" in error:
data = {"error":error}
return JsonResponse(data)
person.download_course_file(course_name)
data = {"success":"Your notes are being downloaded"}
return JsonResponse(data)
PS: create_session is a function for initialising the scraper object with a username and password.
Is there a workaround for this name statement and even if there isn't, can't I remove it when I am deploying to a server as long as the server don't use windows as its OS.

Syntax invalid?

For some reason I keep getting an invalid syntax error of my code on Debian. But when I run it on my mac nothing wrong happens and it runs smooth. Could you guys help me?
def read_config(cfg='~/instacron/config.txt'):
"""Read the config.
Create a config file at `cfg` with the
following information and structure:
my_user_name
my_difficult_password
"""
import os.path
_cfg = os.path.expanduser(cfg)
try:
with open(_cfg, 'r') as f:
user, pw = [s.replace('\n', '') for s in f.readlines()]
except Exception:
import getpass
print(f"\nReading config file `{cfg}` didn't work")
user = input('Enter username and hit enter\n')
pw = getpass.getpass('Enter password and hit enter\n')
save_config = input(
f"Save to config file `{cfg}` (y/N)? ").lower() == 'y'
if save_config:
os.makedirs(os.path.dirname(_cfg), exist_ok=True)
with open(_cfg, 'w') as f:
f.write(f'{user}\n{pw}')
return {'username': user, 'password': pw}`
print(f"\nReading config file `{cfg}` didn't work")
^
SyntaxError: invalid syntax
f-strings (f"{var}") were only added to Python in version 3.6; earlier versions do not accept them. Your Debian and Mac are clearly running different versions of Python, only one of which is at least 3.6.

How to extract Deployed OSB Source code from Environment or SB Console or Weblogic

Could anyone please help me in getting a way to get the source code from Environment or SB Console or Weblogic.
I created the python script whick exports the JAR, but I need the source code. Because if I unjar the jar, I do not get the exact source code, as file names are shorten and some code is added by itself in wsdls, xqueries etc. I don't want that.
Here's my wlst Python/Jython Script:
from java.io import FileInputStream
from java.io import FileOutputStream
from java.util import ArrayList
from java.util import Collections
from com.bea.wli.sb.util import EnvValueTypes
from com.bea.wli.config.env import EnvValueQuery;
from com.bea.wli.config import Ref
from com.bea.wli.config.customization import Customization
from com.bea.wli.config.customization import FindAndReplaceCustomization
import sys
#=======================================================================================
# Utility function to load properties from a config file
#=======================================================================================
def exportAll(exportConfigFile):
def exportAll(exportConfigFile):
try:
print "Loading export config from :", exportConfigFile
exportConfigProp = loadProps(exportConfigFile)
adminUrl = exportConfigProp.get("adminUrl")
exportUser = exportConfigProp.get("exportUser")
exportPasswd = exportConfigProp.get("exportPassword")
exportJar = exportConfigProp.get("exportJar")
customFile = exportConfigProp.get("customizationFile")
passphrase = exportConfigProp.get("passphrase")
project = sys.argv[2]
if project == None :
project = exportConfigProp.get("project")
connectToServer(exportUser, exportPasswd, adminUrl)
ALSBConfigurationMBean = findService("ALSBConfiguration", "com.bea.wli.sb.management.configuration.ALSBConfigurationMBean")
print "ALSBConfiguration MBean found"
print "Input project: ", project
if project == None :
ref = Ref.DOMAIN
collection = Collections.singleton(ref)
if passphrase == None :
print "Export the config"
theBytes = ALSBConfigurationMBean.exportProjects(collection, None)
else :
print "Export and encrypt the config"
theBytes = ALSBConfigurationMBean.export(collection, true, passphrase)
else :
ref = Ref.makeProjectRef(project);
print "Export the project", project
collection = Collections.singleton(ref)
theBytes = ALSBConfigurationMBean.export(collection, false, None)
aFile = File(exportJar)
out = FileOutputStream(aFile)
out.write(theBytes)
out.close()
print "ALSB Configuration file: "+ exportJar + " has been exported"
if customFile != None:
print collection
query = EnvValueQuery(None, Collections.singleton(EnvValueTypes.WORK_MANAGER), collection, false, None, false)
customEnv = FindAndReplaceCustomization('Set the right Work Manager', query, 'Production System Work Manager')
print 'EnvValueCustomization created'
customList = ArrayList()
customList.add(customEnv)
print customList
aFile = File(customFile)
out = FileOutputStream(aFile)
Customization.toXML(customList, out)
out.close()
print "ALSB Dummy Customization file: "+ customFile + " has been created"
except:
raise
#=======================================================================================
# Utility function to load properties from a config file
#=======================================================================================
def loadProps(configPropFile):
propInputStream = FileInputStream(configPropFile)
configProps = Properties()
configProps.load(propInputStream)
return configProps
#=======================================================================================
# Connect to the Admin Server
#=======================================================================================
def connectToServer(username, password, url):
connect(username, password, url)
domainRuntime()
# EXPORT script init
try:
exportAll(sys.argv[1])
except:
print "Unexpected error: ", sys.exc_info()[0]
dumpStack()
raise
Any help would be appreciated.
What you get as a result of the export is the deployed unit. Yes, there is some metadata added/modified as a result of the deployment on the OSB runtime (deployment could also mean creating/editing components directly on the servicebus console).
To get it back as "source code" from the exported jar, you can simply import it back into JDeveloper (12c) or Eclipse with OEPE (11g)

Python os.system(python "program") not working

I'm writing a program with multiple pieces of code, and don't want someone to have to manually copy-paste the entire directory from an install disk, so I've written something that will do it for them (like an autorun).
However, when I try to launch the program after copying it over to the user's computer, I get:
Process finished with exit code 0
instead of the installer booting the program.
This is the def I'm using:
import os
get_project_base_directory()
check_version()
print jason_dir
new_dir = str(jason_dir+"/Jason_Core/Boot.py")
command = "python " + new_dir
print command
os.system(command)
Why might os.system might not be working? I've also tried popopen and subprocess, but the had the same output (exit code 0).
EDIT: I am running this in a script, not the python command line.
EDIT 2: As requested, Boot.py:
# 3rd party libraries
import os
import subprocess
import shutil
from imp import find_module
# My code to import
basedir = ""
# Get the project base directory (drive located on)
def get_project_base_directory():
global basedir
cwd = os.getcwd()
basedir = "/".join(cwd.split("\\")[:len(cwd.split("\\"))-1])
#print basedir
# Copies libraries from disk drive
def copy_libs():
new_dir = "c:/Downloads/Python_Libraries"
if os.path.exists(new_dir):
shutil.rmtree(new_dir)
old_dir = basedir + "/Libraries/Installed"
#print old_dir
try:
shutil.copytree(old_dir, new_dir)
except:
print " Error copying directories! Try manual copy."
print " Go to:", basedir + "/Libraries/Installed"
# Checks to see if the library is installed
def check_lib_install():
temp_var = True
libs_list = ("fbchat", "gtts", "pyaudio", "googlevoice", "espeak", "pywapi", "speech_recognition", "win10toast") # names of libs
for lib in libs_list:
print "Checking lib installation:", lib
try:
__import__(lib)
print " Lib installed"
print ""
except:
print " Lib not installed"
install_lib(lib, libs_list.index(lib))
print "All libraires installed!"
# Install libraries if they don't exist on this machine.
def install_lib(lib, index):
print " Installing lib:", lib
libs_file_list = ("/fbchat-1.0.19/", "/gTTS-1.2.2/", "/PyAudio-0.2.11/", "/pygooglevoice-master/", "/python-espeak-0.5/", "/pywapi-0.3.8/", "/speech_recognition-master/", "/Windows-10-Toast-Notifications-master/") # path to file
print "Installing:", lib
new_dir = "c:/Downloads/Python_Libraries" + libs_file_list[index]
os.chdir(new_dir)
try:
temp_command = "python setup.py install"
subprocess.call(temp_command)
except:
print lib, "failed installation. Try manual install."
print ""
# Gets version number of local copy of Jason, and then the version number of the one on the disk drive. If the local version is lower, the python files are overwritten. If it doesn't yet exist locally, Jason is installed.
def check_version():
local_version = "0"
jason_dir = "C:/Jason_AI" # Where is jason installed to?
if os.path.exists(jason_dir):
with open(jason_dir+"\System Files\Version Number.txt") as local_jason: # Where is jason installed to?
counter = 0
for line in local_jason:
counter += 1
if counter == 2:
local_version = line
#print local_version
elif counter == 3:
break
install_version_file = basedir + "\System Files\Version Number.txt"
install_version_file = "/".join(install_version_file.split("\\"))
with open(install_version_file) as drive_jason:
counter = 0
for line in drive_jason:
counter += 1
if counter == 2:
install_version = line
#print install_version
if install_version == local_version:
print "Version up to date!"
print "Using version number:", local_version
else:
shutil.rmtree(jason_dir)
print "Version outdated"
print "Using version number:", local_version
elif counter == 3:
break
else:
print "Version outdated"
print "Using version number:", local_version
# Controls the boot process, when done, launches into Listen.get_audio()
def control():
get_project_base_directory()
copy_libs()
check_lib_install()
import System_Logins # Importing this here since the required libraries might not be installed if its the first time running Jason on this machine
import Actions # ^^
import System_Commands # ^^
import Listen # ^^
check_version()
logins = System_Logins.read_logins(basedir)
System_Commands.clear_screen()
while True:
speech = Listen.get_audio()
Actions.sort(speech, logins)
def check_packages():
packages = ["System_Logins", "Actions", "System_Commands", "Listen"]
for package in packages:
try:
__import__(package) #Need to work on
print package + ":", "successfully loaded."
packages[packages.index(package)] = "True"
except ImportError:
print package + ":", "error."
return packages
#Remote login (ie, from install)
def remote_control():
packages = check_packages()
#print packages
if any(word in ("System_Logins", "Actions", "System_Commands", "Listen") for word in packages):
control()
import System_Logins # Importing this here since the required libraries might not be installed if its the first time running Jason on this machine
import Actions # ^^
import System_Commands # ^^
import Listen # ^^
logins = System_Logins.read_logins(basedir)
System_Commands.clear_screen()
while True:
speech = Listen.get_audio()
Actions.sort(speech, logins)
remote_control()

Categories

Resources