I am trying to get the Next Run Time of a scheduled task using the ITASKDEFINITION but I am having a trouble getting the NextRunTime I am getting the error
Traceback (most recent call last):
File "WSTC.py", line 34, in <module>
print('NextRun : %s\n' % task.NextRunTime)
ValueError: can't format dates this early
Here is the sample code:
import win32com.client
TASK_ENUM_HIDDEN = 0
TASK_STATE = {0: 'Unknown',
1: 'Disabled',
2: 'Queued',
3: 'Ready',
4: 'Running'}
scheduler = win32com.client.Dispatch('Schedule.Service')
scheduler.Connect()
folders = [scheduler.GetFolder('\\')]
n = 0
while folders:
folder = folders.pop(0)
folders += list(folder.GetFolders(0))
tasks = list(folder.GetTasks(TASK_ENUM_HIDDEN))
for task in tasks:
settings = task.Definition.Settings
if TASK_STATE[task.State] == 'Running':
print('Path : %s' % task.Path)
print('State : %s' % TASK_STATE[task.State])
print('NextRun : %s\n' % task.NextRunTime)
n += 1
print ('Listed %d tasks.' % n)
Any assistance or help on this greatly appreciated. Thanks!
After digging deeper and reading about this error. It seems to be that this issue is only in earlier versions of python (I'm using Python 2.7). I tried upgrading python to the latest version and it returns a date lesser than the year 1900 and no longer throws an ValueError exception.
SOURCES:
1
2
Related
I'm trying to optimize my strategy on Backtrader with python but keeps getting this error and i can't find anything on the web showing why I'm getting it.
My code is simple and loosely based on the quick start examples:
from alpaca_trade_api.rest import REST, TimeFrame, TimeFrameUnit
import backtrader as bt
from config import API_KEY, SECRET_KEY
class EMACross(bt.Strategy):
params = dict(
ema_short_period=5,
ema_long_period=10
)
def __init__(self):
self.order = None
self.short_ma = bt.indicators.ExponentialMovingAverage(period=self.p.ema_short_period)
self.long_ma = bt.indicators.ExponentialMovingAverage(period=self.p.ema_long_period)
self.crossover = bt.ind.CrossOver(self.short_ma, self.long_ma) # crossover signal
self.crossdown = bt.ind.CrossDown(self.short_ma, self.long_ma)
self.crossdown.plotinfo.subplot = False
self.crossover.plotinfo.subplot = False
def next(self):
self.log('Close, %.2f' % self.data.close[0])
if self.position.size > 0:
if self.crossdown > 0:
self.log('SELL CREATE, %.2f' % self.data.close[0])
self.close()
else:
if self.crossover > 0:
self.log('BUY CREATE, %.2f' % self.data.close[0])
self.buy()
def log(self, txt, dt=None):
dt = dt or self.data.datetime.datetime()
print('%s, %s' % (dt.isoformat(), txt))
def stop(self):
self.log('(short EMA Period %2d) (long EMA Period %2d) Ending Value %.2f' %
(self.p.ema_short_period, self.p.ema_long_period, self.broker.getvalue()))
rest_api = REST(API_KEY, SECRET_KEY, 'https://paper-api.alpaca.markets')
def run_backtest(strategy, symbols, start, end, timeframe, cash=100000):
# initialize backtrader broker
cerebro = bt.Cerebro()
cerebro.broker.setcash(cash)
cerebro.addsizer(bt.sizers.PercentSizer, percents=90)
cerebro.optstrategy(strategy, ema_short_period=4, ema_long_period=6)
# historical data request
if type(symbols) == str:
symbol = symbols
alpaca_data = rest_api.get_bars(symbol, timeframe, start, end, adjustment='all').df
data = bt.feeds.PandasData(dataname=alpaca_data, name=symbol)
cerebro.adddata(data)
elif type(symbols) == list or type(symbols) == set:
for symbol in symbols:
alpaca_data = rest_api.get_bars(symbol, timeframe, start, end, adjustment='all').df
data = bt.feeds.PandasData(dataname=alpaca_data, name=symbol)
cerebro.adddata(data)
# run
initial_portfolio_value = cerebro.broker.getvalue()
print(f'Starting Portfolio Value: {initial_portfolio_value}')
results = cerebro.run()
final_portfolio_value = cerebro.broker.getvalue()
print(
f'Final Portfolio Value: {final_portfolio_value} ---> Return: {(final_portfolio_value / initial_portfolio_value - 1) * 100}%')
run_backtest(EMACross, 'QQQ', '2018-01-01', '2022-01-01', TimeFrame(1, TimeFrameUnit.Day))
Running the script, i get this error:
Traceback (most recent call last):
File "/Users/usrname/PycharmProjects/test3/main.py", line 79, in <module>
run_backtest(EMACross, 'QQQ', '2018-01-01', '2022-01-01', TimeFrame(1, TimeFrameUnit.Day))
File "/Users/usrname/PycharmProjects/test3/main.py", line 54, in run_backtest
cerebro.optstrategy(strategy, ema_short_period=4, ema_long_period=6)
File "/Users/usrname/PycharmProjects/test3/venv/lib/python3.10/site-packages/backtrader/cerebro.py", line 893, in optstrategy
vals = self.iterize(kwargs.values())
File "/Users/usrname/PycharmProjects/test3/venv/lib/python3.10/site-packages/backtrader/cerebro.py", line 333, in iterize
elif not isinstance(elem, collections.Iterable):
AttributeError: module 'collections' has no attribute 'Iterable'
Process finished with exit code 1
When running the script without optstrategy() but rather with addstrategy(), evrything is working great. Only when changing to optstrategy is when i'm getting this error.
I also tried to run the same code on Google colab (with optstrategy() method) and everything worked great there, so this got me really puzzled...
I'm running python 3.10 with PyCharm CE on macOS.
Try downgrading from python 3.10 to python 3.8 version
Oh my python guys, please help me.
One of my python projects suddenly stopped working for no reason.
I'm using pytube module and when i try to run the code i get this error:
Traceback (most recent call last):
File "C:\Users\giova\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\contrib\search.py", line 94, in fetch_and_parse
sections = raw_results['contents']['twoColumnSearchResultsRenderer'][
KeyError: 'twoColumnSearchResultsRenderer' fetch_and_parse
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\giova\OneDrive\Desktop\Coding\Python\youtubeapp.py", line 38, in <module>
videoSearch()
File "C:\Users\giova\OneDrive\Desktop\Coding\Python\youtubeapp.py", line 21, in videoSearch
availableResults = len(vid.results)
File "C:\Users\giova\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\contrib\search.py", line 62, in results
videos, continuation = self.fetch_and_parse() results
File "C:\Users\giova\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\contrib\search.py", line 97, in fetch_and_parse fetch_and_parse
sections = raw_results['onResponseReceivedCommands'][0][
KeyError: 'onResponseReceivedCommands'
This is not even the only error i get, sometimes i got "http error 410: gone" error or some like this. I haven't changed the code for about two weeks (it was working two weeks ago) and it stopped working. I don't know what is happening to my code.
This is the full code:
from pytube import Search, YouTube
print("================================\n What do you want to do?: ")
availableChoose = [
'1 Search videos',
'...',
'================================'
]
for choose in availableChoose:
print(choose)
userChoose = input()
userChoose = userChoose.lower()
def videoSearch():
userSearch = input("Enter the title of the video you want to search: ")
vid = Search(userSearch)
availableResults = len(vid.results)
strAvailableResults = str(availableResults)
print("The available results are " + strAvailableResults)
vidResultsList = vid.results
vidResultsList = str(vidResultsList)
vidResultsList = vidResultsList.replace("<pytube.__main__.YouTube object: videoId=", "")
vidResultsList = vidResultsList.replace(">", "")
vidResultsList = vidResultsList.replace("[", "")
vidResultsList = vidResultsList.replace("]", "")
vidResultsList = vidResultsList.replace(" ", "")
vidResultsList = vidResultsList.split(',')
for vidResultsObject in vidResultsList:
vidLink = ("https://www.youtube.com/watch?v=" + vidResultsObject)
vidTempObject = YouTube(vidLink)
print(vidTempObject.title + " - " + vidLink)
if(userChoose == "search" or userChoose == "search video" or userChoose == "search videos" or userChoose == "1"):
videoSearch()
pytube's 11.0.0 API docs list the Search.fetch_and_parse() method.
The corresponding source-code shows that it internally handles a KeyError for onResponseReceivedCommands:
# Initial result is handled by try block, continuations by except block
try:
sections = raw_results['contents']['twoColumnSearchResultsRenderer'][
'primaryContents']['sectionListRenderer']['contents']
except KeyError:
sections = raw_results['onResponseReceivedCommands'][0][
'appendContinuationItemsAction']['continuationItems']
This method is an inner one, that is used by your vid.results call.
Might be, that the Youtube API has changed there response and your version of pytube is not fitting anymore.
Bug already filed
See pytube issue #1082 and issue #1106.
Meanwhile use another branch
tfdahlin's fork has a bugfixed version. It was already proposed as Pull-Request to the project:
PR #1090, opened on 2021-08-13 (currently waiting for approval).
I am also struggling to get around the search results provided by pytube Search module. Since search results are looking like objects, I was thinking (lazily) that I cannot convert the object list in to strings.
After modifying your function as below, the results are printed as youtube links.
'''
def videoSearch(search_list): #provide the search.results list as input
for result in search_list: #Begin video id extraction
result = str(result)
temp = result.replace("<pytube.__main__.YouTube object: videoId=", "")
temp = temp.split(',')[0] #get the correct video id
vidLink = ("https://www.youtube.com/watch?v=" + temp)
print(vidLink)
'''
Try it out.
I hope someone can help me. I've been stuck with this error for a while. I have two .py files that I am importing in a jupyter notebook. When running the last cell (see code below) I get a Traceback error I can'f fix.
I think there is some error in my ch_data_prep.py file related to variable df_ch not correctly passed between files. Is this possible? Any suggestion on how to solve this problem?
Thanks!
ch_data_prep.py
def seg_data(self):
seg_startdate = input('Enter start date (yyyy-mm-dd): ')
seg_finishdate = input('Enter end date (yyyy-mm-dd): ')
df_ch_seg = df_ch[(df_ch['event_datetime'] > seg_startdate)
& (df_ch['event_datetime'] < seg_finishdate)
]
return df_ch_seg
df_ch_seg = seg_data(df_ch)
ch_db.py
def get_data():
# Some omitted code here to connect to database and get data...
df_ch = pd.DataFrame(result)
return df_ch
df_ch = get_data()
Jupyter Notebook data_analysis.ipynb
In[1]: import ch_db
df_ch = ch_db.get_data()
In[2]: import ch_data_prep
When I run cell 2, I get this error
--------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-fbe2d4fceba6> in <module>
----> 1 import ch_data_prep
~/clickstream/ch_data_prep.py in <module>
34 return df_ch_seg
35
---> 36 df_ch_seg = seg_data()
TypeError: seg_data() missing 1 required positional argument: 'df_ch'
When trying to create a conditional statement i get this error. I have tried many things over the last week to get this working but everything i try is failing.
Can anyone shed some light if this is specific to pynmea nodule?
def parse_gps(incoming_data):
if incoming_data.find("GGA") > 0:
data = pynmea2.parse(incoming_data)
print("Timestamp: %s // Lat: %s // Lon: %s // Satellites: %s " % (data.timestamp, data.latitude,
data.longitude, data.num_sats))
return data
while True:
gps_fix = ser.readline().decode('ascii')
gps_data = parse_gps(gps_fix)
if gps_data.num_sats > 7:
break
else:
print("No data")```
Should find a fix of satellites greater than 7 in order to gain a valid fix then break.
while True:
gps_fix = ser.readline().decode('ascii')
gps_data = parse_gps(gps_fix)
if gps_data is not None and int(gps_data.num_sats) > 7:
break```
After a few errors about str and int i finally managed to work out the fix.
I'm bukkit jython/python plugin programmer. Last few days, I'm struggling with this problem. I have to add an potion effect to an user, it's not problem if I enter effect name, duration and amplifier manually in code, but when I want to get them from config, I get this error:
13:38:20 [SEVERE] Could not pass event PlayerInteractEvent to ItemEffect v1.0
Traceback (most recent call last):
File "<iostream>", line 126, in onPlayerInteractEvent
TypeError: addPotionEffect(): 1st arg can't be coerced to org.bukkit.potion.Poti
onEffect
Here's that part of code:
effectname = section.getString("%s.effect"%currentKey)
duration = section.getInt("%s.duration"%currentKey)
durationinticks = duration * 20
geteffectname = "PotionEffectType.%s"%effectname
getpotioneffect = "PotionEffect(%s, %i, 1)"%(geteffectname, durationinticks)
geteffectname = "PotionEffectType.%s"%effectname
if iteminhand == currentKey:
event.getPlayer().addPotionEffect(getpotioneffect)
When I print getpotioneffect out, I get:
13:38:20 [INFO] PotionEffect(PotionEffectType.SPEED, 600, 1)
which is okay, and should work. I tested it without getting informations from config, and it works perfectly... To sum up, code above is not working, but below one works:
getpotioneffect = PotionEffect(PotionEffectType.SPEED, 600, 1)
if iteminhand == currentKey:
event.getPlayer().addPotionEffect(getpotioneffect)
Link to javadocs of this event!
http://jd.bukkit.org/rb/apidocs/org/bukkit/entity/LivingEntity.html#addPotionEffect(org.bukkit.potion.PotionEffect)
Thanks!
In your first snippet, getpotioneffect is a string. You can check it adding print type(getpotioneffect) somewhere.
What you want is to replace this :
geteffectname = "PotionEffectType.%s"%effectname
getpotioneffect = "PotionEffect(%s, %i, 1)"%(geteffectname, durationinticks)
with this:
effect_type = getattr(PotionEffectType, effectname)
potion_effect = PotionEffect(effect_type, durationinticks, 1)