supervisor can't import schedule - python-3.x

I try use instead time.sleep schedule functions but I have error
package containing module schedule is not listed in project
requirements
in file with error it's look like
supervisor: couldn't exec
/home/darek/PycharmProjects/Small_programs/shell_scripts/test/test_s.py:
ENOEXEC supervisor: child process was not spawned
when I use code:
import requests, time, schedule, threading
from my_status import *
def superviorTask():
r = requests.get('https://medium.com')
if r.status_code == 200 and len(r.text) > 0:
status = STATUS_LIVE
else:
status = STATUS_INACTIVE # record to my database that the supervisor is running
def threadTask(job_function):
job_thread = threading.Thread(target=job_function)
job_thread.start()
# start schedule
schedule.every(10).minutes.do(threadTask, superviorTask)
while 1:
schedule.run_pending()
time.sleep(1)
and when I try below:
#!/usr/bin/env python3.6
from datetime import datetime
import time
import sys
import schedule
schedule.every(10).seconds.do(print("schedule tests!"))
while True:
print(f"You run test program using Supervisor at {datetime.now().strftime('%H-%M-%S')}.")
print("Good job Darek :)!!!")
print("...")
time.sleep(5)
I have error:
import schedule ModuleNotFoundError: No module named 'schedule'
Traceback (most recent call last): File
"/home/darek/PycharmProjects/Small_programs/shell_scripts/test/test_s.py",
line 5, in import schedule ModuleNotFoundError: No module
named 'schedule' Traceback (most recent call last):
File"/home/darek/PycharmProjects/Small_programs/shell_scripts/test/test_s.py",
line 5, in import schedule ModuleNotFoundError: No module
named 'schedule'

The default version of schedule package in python 2.7
If you have 3. version forward, you need to specify it:
pip3 install schedule (at CMD)

Related

ModuleNotFoundError: No module named in PyCharm

I was able to run the project using the command line, but from last 1 day I am not able to run the command from the command line However using GUI the project is running fine...
C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\Tests>py
thon login.py
Traceback (most recent call last):
File "login.py", line 6, in <module>
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
ModuleNotFoundError: No module named 'SampleProjects'
C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\Tests>py
thon -m unittest login.py
E
======================================================================
ERROR: login (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: login
Traceback (most recent call last):
File "C:\Users\tester\AppData\Local\Programs\Python\Python37-32\lib\unittest\
loader.py", line 154, in loadTestsFromName
module = __import__(module_name)
File "C:\Users\tester\PycharmProjects\Selenium\SampleProjects\POMProjectDemo\
Tests\login.py", line 6, in <module>
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
ModuleNotFoundError: No module named 'SampleProjects'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
[![Tests/login.py
import time
from selenium import webdriver
import unittest
from selenium.common.exceptions import NoSuchElementException
from SampleProjects.POMProjectDemo.Pages.loginPage import LoginPage
from SampleProjects.POMProjectDemo.Pages.homePage import HomePage
import HtmlTestRunner
from SampleProjects.POMProjectDemo.Utility.XLUtil import getData
class LoginTest(unittest.TestCase):
#classmethod
def setUpClass(cls):
cls.driver = webdriver.Chrome(executable_path='F:/Selenium/chromedriver.exe')
cls.driver.implicitly_wait(10)
cls.driver.maximize_window()
def test_login_valid(self):
path = 'c:/Users/mahmood/PycharmProjects/Selenium_automaton/Login.xlsx'
# global path
driver = self.driver
row = getData.getRowCount(path,'Sheet1')
for r in range(2,row+1):
driver.get("https://opensource-demo.orangehrmlive.com/")
userN = getData.readData(path,'Sheet1',r,1)
passW = getData.readData(path,'Sheet1',r,2)
Same code was running fine, what changes I have done not able to debug it.

Cyclic import in Python3

I have the following directory structure:
my-game/
__init__.py
logic/
__init__.py
game.py
player.py
game.py and player.py have import dependency on each other (cyclic imports).
game.py has the following definition.
from logic.player import RandomPlayer, InteractivePlayer
T = 8
class Game:
def __init__(self, p1, p2)
...
# some other things
if __name__ == '__main__':
p1 = RandomPlayer()
p2 = InteractivePlayer()
g = Game(p1, p2)
...
player.py is as follows:
from logic.game import T
class Player:
def __init__(self):
...
class RandomPlayer(Player):
def __init__(self):
...
class InteractivePlayer(Player):
def __init__(self):
...
I am trying to run the game from logic/ directory but I get the following error.
$ python3 game.py
Traceback (most recent call last):
File "game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
I then tried running game.py from the directory higher up (my-game/).
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'
What am I doing wrong? How can I make these cyclic imports work?
I have also tried using this import in player.py
from .game import T
and using
from .player import RandomPlayer, InteractivePlayer
in game.py.
In this case, I get a different error. For example, when running from my-game/,
$ python3 logic/game.py
Traceback (most recent call last):
File "logic/game.py", line 2, in <module>
from .player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named '__main__.player'; '__main__' is not a package
I get a similar error when running from logic/ directory.
I looked at this post but didn't understand where I was going wrong.
You are made a circulair import in your code try to remove it from your import
Vist this link you can find some other info about circular import :Remove python circular import

Unable to restore job - apscheduler, sqlalchemy

I'm trying to write my own little python flask app to monitor the hard drives of my server.
But since now, I'm getting trouble using the sqljobstore of apscheduler.
While the server is running, everything is fine. But after a restart, I can't access the web interface and getting the folowing output:
Unable to restore job "refresh_disks" -- removing it
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/apscheduler/util.py", line 289, in ref_to_obj
obj = getattr(obj, name)
AttributeError: module 'dirkules.tasks' has no attribute 'refresh_disks'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/apscheduler/jobstores/sqlalchemy.py", line 141, in _get_jobs
jobs.append(self._reconstitute_job(row.job_state))
File "/usr/local/lib/python3.6/dist-packages/apscheduler/jobstores/sqlalchemy.py", line 128, in _reconstitute_job
job.__setstate__(job_state)
File "/usr/local/lib/python3.6/dist-packages/apscheduler/job.py", line 272, in __setstate__
self.func = ref_to_obj(self.func_ref)
File "/usr/local/lib/python3.6/dist-packages/apscheduler/util.py", line 292, in ref_to_obj
raise LookupError('Error resolving reference %s: error looking up object' % ref)
LookupError: Error resolving reference dirkules.tasks:refresh_disks: error looking up object
[2019-04-26 15:46:39 +0200] [13296] [INFO] Shutting down: Master
Here is my config.py:
import os
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
#from apscheduler.jobstores.memory import MemoryJobStore
baseDir = os.path.abspath(os.path.dirname(__file__))
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(baseDir, 'dirkules.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False
# The SCHEDULER_JOB_DEFAULTS configuration is per job, that means each job can execute at most 3 threads at the same time.
# The SCHEDULER_EXECUTORS is a global configuration, in this case, only 1 thread will be used for all the jobs.
# I believe the best way for you is to use max_workers: 1 when running locally
SCHEDULER_JOBSTORES = {'default': SQLAlchemyJobStore(url='sqlite:///' + os.path.join(baseDir, 'dirkules.db'))}
#SCHEDULER_JOBSTORES = {'default': MemoryJobStore()}
SCHEDULER_EXECUTORS = {'default': {'type': 'threadpool', 'max_workers': 3}}
SCHEDULER_JOB_DEFAULTS = {'coalesce': False, 'max_instances': 1}
SCHEDULER_API_ENABLED = True
init.py:
import dirkules.config as config
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_apscheduler import APScheduler
app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)
import dirkules.models
db.create_all()
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
##app.before_first_request
from dirkules import tasks
# from dirkules.models import Time
# from sqlalchemy.orm.exc import NoResultFound
#
# try:
# Time.query.one()
# except NoResultFound:
# db.session.add(Time("Drives"))
# db.session.commit()
import dirkules.views
and tasks.py:
from dirkules import scheduler
import datetime
import dirkules.driveManagement.driveController as drico
#scheduler.task('interval', id='refresh_disks', seconds=10)
def refresh_disks():
#drives = drico.getAllDrives()
print("Drives refreshed")
Hopefully, you can help me!
Starting the scheduler as a side-effect of importing the module is considered bad practice and is also the likely reason why the attribute lookup fails. I would have to see a simplified, more complete example that reproduces the problem to be sure, however.

ModuleNotFoundError: No module named 'getpwnam'

I want to use the following code to change the owner of files:
import os
from getpwnam import pwd
from getgrnam import grp
uid = getpwnam('edamame')[2]
gid = grp.getgrnam('staff')[2]
os.chown('/Users/edamame/workspace/git/chinese_nlp/venv/lib/python3.7/site-packages/psutil/_psosx.py', uid, gid)
But the following errors:
Traceback (most recent call last):
File "/Users/edamame/workspace/git/chinese_nlp/chinese_segmenter1.py", line 6, in <module>
from getpwnam import pwd
ModuleNotFoundError: No module named 'getpwnam'
Process finished with exit code 1
I am using Python 3.7 virtual env in PyCharm. I couldn't find the module called getpwnam to install. Which package should I install? Thanks!
You got the imports a bit backwards, I know, it happens :) Try this (pwd and grp are just standard Python library modules):
>>> from pwd import getpwnam
>>> getpwnam('root')[2]
0
>>> from grp import getgrnam
>>> getgrnam('root')[2]
0

Python version related error

I am trying to generate an HTML test report by using Selenium webdriver library HTMLTestRunner. I am using Python 3.4 version and I have a version related error. Refer following snippet.
import unittest`enter code here`
import HTMLTestRunner
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.keys import Keys
class GreenlamTest(unittest.TestCase):
#classmethod
def setUp(cls):
cls.driver=webdriver.Firefox()
cls.driver.implicitly_wait(30)
cls.driver.maximize_window()
cls.driver.get('https://www.google.co.in')
def test_checkTitle(self):
assert "Google" in self.driver.title
def test_searchtest(self):
driver = self.driver
elem = self.driver.find_element_by_name("q")
elem.send_keys("pycon")
elem.send_keys(Keys.RETURN)
#classmethod
def tearDown(cls):
cls.driver.quit()
if __name__ == '__main__':
HTMLTestRunner.main
Output
Finding files... done.
Traceback (most recent call last):
File "C:\Users\vaibhav\Desktop\Selenium Softwares\eclipse-jee-luna-SR2-win32-x86_64\eclipse\plugins\org.python.pydev_4.0.0.201504132356\pysrc\pydev_runfiles.py", line 468, in __get_module_from_str
mod = __import__(modname)
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py", line 2, in <module>
import HTMLTestRunner
File "C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\HTMLTestRunner.py", line 94, in <module>
import StringIO
ImportError: No module named 'StringIO'
ERROR: Module: Htmlreport could not be imported (file: C:\Users\vaibhav\Desktop\Selenium Softwares\Practice\pythondemo\Htmlreport.py).
Importing test modules ... done.
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
You are getting error because your folder name Selenium Softwares has a space in it where your Htmlreport is present. Replace the folder name to exclude space out of it, probably an underscore or camelCase, etc... like this Selenium_Softwares . Here's how -
file: C:\Users\vaibhav\Desktop\Selenium_Softwares\Practice\pythondemo\Htmlreport.py)
Hope this helps.

Resources