after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def getUser(self, username, **kwargs) -> dict: """Gets the full exposed user object :param username: The username of the user. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, did, ) = self.__process_kwargs__(kwargs) kwargs["custom_did"] = did query = { "uniqueId": username, "language": language, "isUniqueId": True, "validUniqueId": username, } api_url = "{}node/share/user/@{}?{}&{}".format( BASE_URL, quote(username), self.__add_new_params__(), urlencode(query) ) return self.getData(url=api_url, **kwargs)["userInfo"]
def getUser(self, username, **kwargs) -> dict: """Gets the full exposed user object :param username: The username of the user. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, did, ) = self.__process_kwargs__(kwargs) kwargs["custom_did"] = did query = {"language": language} api_url = "{}node/share/user/@{}?{}&{}".format( BASE_URL, quote(username), self.__add_new_params__(), urlencode(query) ) return self.getData(url=api_url, **kwargs)["userInfo"]
https://github.com/davidteather/TikTok-Api/issues/338
Invalid Response Traceback (most recent call last): File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 162, in getData return r.json() File "/home/user/.local/lib/python3.8/site-packages/requests/models.py", line 898, in json return complexjson.loads(self.text, **kwargs) File "/usr/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/user/tiktok/tiktokhelper.py", line 33, in addUser data = api.getUser(uniqueId) File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 1010, in getUser return self.getData(url=api_url, **kwargs)["userInfo"] File "/home/user/.local/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 170, in getData raise Exception("Invalid Response") Exception: Invalid Response
json.decoder.JSONDecodeError
def trending(self, count=30, minCursor=0, maxCursor=0, **kwargs) -> dict: """ Gets trending TikToks """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": 1, "secUid": "", "maxCursor": maxCursor, "minCursor": minCursor, "sourceType": 12, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, **kwargs) for t in res.get("items", []): response.append(t) if not res["hasMore"] and not first: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response[:count] realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
def trending(self, count=30, minCursor=0, maxCursor=0, **kwargs) -> dict: """ Gets trending TikToks """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": 1, "secUid": "", "maxCursor": maxCursor, "minCursor": minCursor, "sourceType": 12, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, proxy=proxy) for t in res.get("items", []): response.append(t) if not res["hasMore"] and not first: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response[:count] realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def discover_type(self, search_term, prefix, count=28, **kwargs) -> list: """Returns a list of whatever the prefix type you pass in :param search_term: The string to search by. :param prefix: The type of post to search by user/music/challenge. :param count: The number of posts to return. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] offsetCount = 0 while len(response) < count: query = { "discoverType": count, "needItemList": False, "keyWord": search_term, "offset": offsetCount, "count": 99, "useRecommend": False, "language": "en", } api_url = "{}api/discover/{}/?{}&{}".format( BASE_URL, prefix, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) data = self.getData(b, **kwargs) if "userInfoList" in data.keys(): for x in data["userInfoList"]: response.append(x) elif "musicInfoList" in data.keys(): for x in data["musicInfoList"]: response.append(x) elif "challengeInfoList" in data.keys(): for x in data["challengeInfoList"]: response.append(x) else: if self.debug: print("Nomore results being returned") break offsetCount = len(response) return response[:count]
def discover_type(self, search_term, prefix, count=28, **kwargs) -> list: """Returns a list of whatever the prefix type you pass in :param search_term: The string to search by. :param prefix: The type of post to search by user/music/challenge. :param count: The number of posts to return. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] offsetCount = 0 while len(response) < count: query = { "discoverType": count, "needItemList": False, "keyWord": search_term, "offset": offsetCount, "count": 99, "useRecommend": False, "language": "en", } api_url = "{}api/discover/{}/?{}&{}".format( BASE_URL, prefix, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) data = self.getData(b, proxy=proxy) if "userInfoList" in data.keys(): for x in data["userInfoList"]: response.append(x) elif "musicInfoList" in data.keys(): for x in data["musicInfoList"]: response.append(x) elif "challengeInfoList" in data.keys(): for x in data["challengeInfoList"]: response.append(x) else: if self.debug: print("Nomore results being returned") break offsetCount = len(response) return response[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def userPosts( self, userID, secUID, count=30, minCursor=0, maxCursor=0, **kwargs ) -> dict: """Returns a dictionary listing TikToks given a user's ID and secUID :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": userID, "type": 1, "secUid": secUID, "maxCursor": maxCursor, "minCursor": minCursor, "sourceType": 8, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, **kwargs) if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
def userPosts( self, userID, secUID, count=30, minCursor=0, maxCursor=0, **kwargs ) -> dict: """Returns a dictionary listing TikToks given a user's ID and secUID :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": userID, "type": 1, "secUid": secUID, "maxCursor": maxCursor, "minCursor": minCursor, "sourceType": 8, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, proxy=proxy) if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def byUsername(self, username, count=30, **kwargs) -> dict: """Returns a dictionary listing TikToks given a user's username. :param username: The username of the user. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) data = self.getUserObject(username, **kwargs) return self.userPosts( data["id"], data["secUid"], count=count, **kwargs, )
def byUsername(self, username, count=30, **kwargs) -> dict: """Returns a dictionary listing TikToks given a user's username. :param username: The username of the user. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) data = self.getUserObject(username, proxy=proxy) return self.userPosts( data["id"], data["secUid"], count=count, proxy=proxy, language=language, region=region, **kwargs, )
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def userPage( self, userID, secUID, page_size=30, minCursor=0, maxCursor=0, **kwargs ) -> dict: """Returns a dictionary listing of one page of TikToks given a user's ID and secUID :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param page_size: The number of posts to return per page. :param minCursor: time stamp for the earliest TikTok to retrieve :param maxCursor: time stamp for the latest TikTok to retrieve :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) api_url = ( "https://m.tiktok.com/api/item_list/?{}&count={}&id={}&type=1&secUid={}" "&minCursor={}&maxCursor={}&sourceType=8&appId=1233&region={}&language={}".format( self.__add_new_params__(), page_size, str(userID), str(secUID), minCursor, maxCursor, region, language, ) ) b = browser(api_url, **kwargs) return self.getData(b, **kwargs)
def userPage( self, userID, secUID, page_size=30, minCursor=0, maxCursor=0, **kwargs ) -> dict: """Returns a dictionary listing of one page of TikToks given a user's ID and secUID :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param page_size: The number of posts to return per page. :param minCursor: time stamp for the earliest TikTok to retrieve :param maxCursor: time stamp for the latest TikTok to retrieve :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) api_url = ( "https://m.tiktok.com/api/item_list/?{}&count={}&id={}&type=1&secUid={}" "&minCursor={}&maxCursor={}&sourceType=8&appId=1233&region={}&language={}".format( self.__add_new_params__(), page_size, str(userID), str(secUID), minCursor, maxCursor, region, language, ) ) b = browser(api_url, **kwargs) return self.getData(b, proxy=proxy)
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getUserPager(self, username, page_size=30, minCursor=0, maxCursor=0, **kwargs): """Returns a generator to page through a user's feed :param username: The username of the user. :param page_size: The number of posts to return in a page. :param minCursor: time stamp for the earliest TikTok to retrieve :param maxCursor: time stamp for the latest TikTok to retrieve :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) data = self.getUserObject(username, **kwargs) while True: resp = self.userPage( data["id"], data["secUid"], page_size=page_size, maxCursor=maxCursor, minCursor=minCursor, **kwargs, ) try: page = resp["items"] except KeyError: # No mo results return maxCursor = resp["maxCursor"] yield page if not resp["hasMore"]: return # all done
def getUserPager(self, username, page_size=30, minCursor=0, maxCursor=0, **kwargs): """Returns a generator to page through a user's feed :param username: The username of the user. :param page_size: The number of posts to return in a page. :param minCursor: time stamp for the earliest TikTok to retrieve :param maxCursor: time stamp for the latest TikTok to retrieve :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) data = self.getUserObject(username, proxy=proxy) while True: resp = self.userPage( data["id"], data["secUid"], page_size=page_size, maxCursor=maxCursor, minCursor=minCursor, proxy=proxy, language=language, region=region, ) try: page = resp["items"] except KeyError: # No mo results return maxCursor = resp["maxCursor"] yield page if not resp["hasMore"]: return # all done
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def userLiked( self, userID, secUID, count=30, minCursor=0, maxCursor=0, **kwargs ) -> dict: """Returns a dictionary listing TikToks that a given a user has liked. Note: The user's likes must be public :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": userID, "type": 2, "secUid": secUID, "maxCursor": maxCursor, "minCursor": minCursor, "sourceType": 9, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, **kwargs) try: res["items"] except Exception: if self.debug: print("Most Likely User's List is Empty") return [] if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
def userLiked( self, userID, secUID, count=30, minCursor=0, maxCursor=0, **kwargs ) -> dict: """Returns a dictionary listing TikToks that a given a user has liked. Note: The user's likes must be public :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": userID, "type": 2, "secUid": secUID, "maxCursor": maxCursor, "minCursor": minCursor, "sourceType": 9, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, proxy=proxy) try: res["items"] except Exception: if self.debug: print("Most Likely User's List is Empty") return [] if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def userLikedbyUsername(self, username, count=30, **kwargs) -> dict: """Returns a dictionary listing TikToks a user has liked by username. Note: The user's likes must be public :param username: The username of the user. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) data = self.getUserObject(username, **kwargs) return self.userLiked( data["id"], data["secUid"], count=count, **kwargs, )
def userLikedbyUsername(self, username, count=30, **kwargs) -> dict: """Returns a dictionary listing TikToks a user has liked by username. Note: The user's likes must be public :param username: The username of the user. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) data = self.getUserObject(username, proxy=proxy) return self.userLiked( data["id"], data["secUid"], count=count, proxy=proxy, language=language, region=region, **kwargs, )
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def bySound(self, id, count=30, offset=0, **kwargs) -> dict: """Returns a dictionary listing TikToks with a specific sound. :param id: The sound id to search by. Note: Can be found in the URL of the sound specific page or with other methods. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "secUid": "", "musicID": str(id), "count": str(realCount), "cursor": str(offset), "shareUid": "", "language": language, } api_url = "{}api/music/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, **kwargs) for t in res.get("itemList", []): response.append(t) if not res["hasMore"]: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) offset = res["cursor"] return response[:count]
def bySound(self, id, count=30, offset=0, **kwargs) -> dict: """Returns a dictionary listing TikToks with a specific sound. :param id: The sound id to search by. Note: Can be found in the URL of the sound specific page or with other methods. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "secUid": "", "musicID": str(id), "count": str(realCount), "cursor": str(offset), "shareUid": "", "language": language, } api_url = "{}api/music/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, proxy=proxy) for t in res.get("itemList", []): response.append(t) if not res["hasMore"]: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) offset = res["cursor"] return response[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getMusicObject(self, id, **kwargs) -> dict: """Returns a music object for a specific sound id. :param id: The sound id to search by. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"musicId": id, "language": language} api_url = "{}api/music/detail/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, **kwargs)
def getMusicObject(self, id, **kwargs) -> dict: """Returns a music object for a specific sound id. :param id: The sound id to search by. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"musicId": id, "language": language} api_url = "{}api/music/detail/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, proxy=proxy)
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def byHashtag(self, hashtag, count=30, offset=0, **kwargs) -> dict: """Returns a dictionary listing TikToks with a specific hashtag. :param hashtag: The hashtag to search by. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) id = self.getHashtagObject(hashtag)["challengeInfo"]["challenge"]["id"] response = [] required_count = count while len(response) < required_count: if count > maxCount: count = maxCount query = { "count": count, "challengeID": id, "type": 3, "secUid": "", "cursor": offset, "sourceType": "8", "language": language, } api_url = "{}api/challenge/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, **kwargs) try: for t in res["itemList"]: response.append(t) except: if self.debug: print(res) if not res["hasMore"]: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response offset += maxCount return response[:required_count]
def byHashtag(self, hashtag, count=30, offset=0, **kwargs) -> dict: """Returns a dictionary listing TikToks with a specific hashtag. :param hashtag: The hashtag to search by. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) id = self.getHashtagObject(hashtag)["challengeInfo"]["challenge"]["id"] response = [] required_count = count while len(response) < required_count: if count > maxCount: count = maxCount query = { "count": count, "challengeID": id, "type": 3, "secUid": "", "cursor": offset, "sourceType": "8", "language": language, } api_url = "{}api/challenge/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, proxy=proxy, language=language) try: for t in res["itemList"]: response.append(t) except: if self.debug: print(res) if not res["hasMore"]: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response offset += maxCount return response[:required_count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getHashtagObject(self, hashtag, **kwargs) -> dict: """Returns a hashtag object. :param hashtag: The hashtag to search by. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"challengeName": hashtag, "language": language} api_url = "{}api/challenge/detail/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, **kwargs)
def getHashtagObject(self, hashtag, **kwargs) -> dict: """Returns a hashtag object. :param hashtag: The hashtag to search by. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"challengeName": hashtag, "language": language} api_url = "{}api/challenge/detail/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, proxy=proxy)
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getHashtagDetails(self, hashtag, **kwargs) -> dict: """Returns a hashtag object. :param hashtag: The hashtag to search by. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"language": language} api_url = "{}node/share/tag/{}?{}&{}".format( BASE_URL, quote(hashtag), self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, **kwargs)
def getHashtagDetails(self, hashtag, **kwargs) -> dict: """Returns a hashtag object. :param hashtag: The hashtag to search by. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"language": language} api_url = "{}node/share/tag/{}?{}&{}".format( BASE_URL, quote(hashtag), self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, proxy=proxy)
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getRecommendedTikToksByVideoID( self, id, count=30, minCursor=0, maxCursor=0, **kwargs ) -> dict: """Returns a dictionary listing reccomended TikToks for a specific TikTok video. :param id: The id of the video to get suggestions for. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": 1, "secUid": "", "maxCursor": maxCursor, "minCursor": minCursor, "sourceType": 12, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/recommend/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, **kwargs) for t in res.get("items", []): response.append(t) if not res["hasMore"] and not first: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response[:count] realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
def getRecommendedTikToksByVideoID( self, id, count=30, minCursor=0, maxCursor=0, **kwargs ) -> dict: """Returns a dictionary listing reccomended TikToks for a specific TikTok video. :param id: The id of the video to get suggestions for. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) response = [] first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": 1, "secUid": "", "maxCursor": maxCursor, "minCursor": minCursor, "sourceType": 12, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/recommend/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = self.getData(b, proxy=proxy) for t in res.get("items", []): response.append(t) if not res["hasMore"] and not first: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response[:count] realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getTikTokById(self, id, **kwargs) -> dict: """Returns a dictionary of a specific TikTok. :param id: The id of the TikTok you want to get the object for. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) did = kwargs.get("custom_did", None) query = { "itemId": id, "language": language, } api_url = "{}api/item/detail/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, **kwargs)
def getTikTokById(self, id, **kwargs) -> dict: """Returns a dictionary of a specific TikTok. :param id: The id of the TikTok you want to get the object for. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) did = kwargs.get("custom_did", None) query = { "itemId": id, "language": language, } api_url = "{}api/item/detail/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, proxy=proxy)
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def discoverHashtags(self, **kwargs) -> dict: """Discover page, consists challenges (hashtags) :param proxy: The IP address of a proxy server. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"noUser": 1, "userCount": 30, "scene": 0} api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, **kwargs)["body"][1]["exploreList"]
def discoverHashtags(self, **kwargs) -> dict: """Discover page, consists challenges (hashtags) :param proxy: The IP address of a proxy server. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"noUser": 1, "userCount": 30, "scene": 0} api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, proxy=proxy)["body"][1]["exploreList"]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def discoverMusic(self, **kwargs) -> dict: """Discover page, consists of music :param proxy: The IP address of a proxy server. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"noUser": 1, "userCount": 30, "scene": 0} api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, **kwargs)["body"][2]["exploreList"]
def discoverMusic(self, **kwargs) -> dict: """Discover page, consists of music :param proxy: The IP address of a proxy server. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"noUser": 1, "userCount": 30, "scene": 0} api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, proxy=proxy)["body"][2]["exploreList"]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getUser(self, username, **kwargs) -> dict: """Gets the full exposed user object :param username: The username of the user. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"uniqueId": username, "language": language} api_url = "{}api/user/detail/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, **kwargs)["userInfo"]
def getUser(self, username, **kwargs) -> dict: """Gets the full exposed user object :param username: The username of the user. :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = {"uniqueId": username, "language": language} api_url = "{}api/user/detail/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) return self.getData(b, proxy=proxy)["userInfo"]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getSuggestedUsersbyID( self, userId="6745191554350760966", count=30, **kwargs ) -> list: """Returns suggested users given a different TikTok user. :param userId: The id of the user to get suggestions for. :param count: The amount of users to return. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = { "noUser": 0, "pageId": userId, "userId": userId, "userCount": count, "scene": 15, } api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = [] for x in self.getData(b, **kwargs)["body"][0]["exploreList"]: res.append(x["cardItem"]) return res[:count]
def getSuggestedUsersbyID( self, userId="6745191554350760966", count=30, **kwargs ) -> list: """Returns suggested users given a different TikTok user. :param userId: The id of the user to get suggestions for. :param count: The amount of users to return. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = { "noUser": 0, "pageId": userId, "userId": userId, "userCount": count, "scene": 15, } api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = [] for x in self.getData(b, proxy=proxy)["body"][0]["exploreList"]: res.append(x["cardItem"]) return res[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getSuggestedUsersbyIDCrawler( self, count=30, startingId="6745191554350760966", **kwargs ) -> list: """Crawls for listing of all user objects it can find. :param count: The amount of users to crawl for. :param startingId: The ID of a TikTok user to start at. :param language: The language parameter. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) users = [] unusedIDS = [startingId] while len(users) < count: userId = random.choice(unusedIDS) newUsers = self.getSuggestedUsersbyID(userId=userId, **kwargs) unusedIDS.remove(userId) for user in newUsers: if user not in users: users.append(user) unusedIDS.append(user["id"]) return users[:count]
def getSuggestedUsersbyIDCrawler( self, count=30, startingId="6745191554350760966", **kwargs ) -> list: """Crawls for listing of all user objects it can find. :param count: The amount of users to crawl for. :param startingId: The ID of a TikTok user to start at. :param language: The language parameter. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) users = [] unusedIDS = [startingId] while len(users) < count: userId = random.choice(unusedIDS) newUsers = self.getSuggestedUsersbyID( userId=userId, language=language, proxy=proxy ) unusedIDS.remove(userId) for user in newUsers: if user not in users: users.append(user) unusedIDS.append(user["id"]) return users[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getSuggestedHashtagsbyID( self, count=30, userId="6745191554350760966", **kwargs ) -> list: """Returns suggested hashtags given a TikTok user. :param userId: The id of the user to get suggestions for. :param count: The amount of users to return. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = { "noUser": 0, "pageId": userId, "userId": userId, "userCount": count, "scene": 15, } api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = [] for x in self.getData(b, **kwargs)["body"][1]["exploreList"]: res.append(x["cardItem"]) return res[:count]
def getSuggestedHashtagsbyID( self, count=30, userId="6745191554350760966", **kwargs ) -> list: """Returns suggested hashtags given a TikTok user. :param userId: The id of the user to get suggestions for. :param count: The amount of users to return. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = { "noUser": 0, "pageId": userId, "userId": userId, "userCount": count, "scene": 15, } api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = [] for x in self.getData(b, proxy=proxy)["body"][1]["exploreList"]: res.append(x["cardItem"]) return res[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getSuggestedHashtagsbyIDCrawler( self, count=30, startingId="6745191554350760966", **kwargs ) -> list: """Crawls for as many hashtags as it can find. :param count: The amount of users to crawl for. :param startingId: The ID of a TikTok user to start at. :param language: The language parameter. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) hashtags = [] ids = self.getSuggestedUsersbyIDCrawler( count=count, startingId=startingId, **kwargs ) while len(hashtags) < count and len(ids) != 0: userId = random.choice(ids) newTags = self.getSuggestedHashtagsbyID(userId=userId["id"], **kwargs) ids.remove(userId) for hashtag in newTags: if hashtag not in hashtags: hashtags.append(hashtag) return hashtags[:count]
def getSuggestedHashtagsbyIDCrawler( self, count=30, startingId="6745191554350760966", **kwargs ) -> list: """Crawls for as many hashtags as it can find. :param count: The amount of users to crawl for. :param startingId: The ID of a TikTok user to start at. :param language: The language parameter. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) hashtags = [] ids = self.getSuggestedUsersbyIDCrawler( count=count, startingId=startingId, language=language, proxy=proxy ) while len(hashtags) < count and len(ids) != 0: userId = random.choice(ids) newTags = self.getSuggestedHashtagsbyID( userId=userId["id"], language=language, proxy=proxy ) ids.remove(userId) for hashtag in newTags: if hashtag not in hashtags: hashtags.append(hashtag) return hashtags[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getSuggestedMusicbyID( self, count=30, userId="6745191554350760966", **kwargs ) -> list: """Returns suggested music given a TikTok user. :param userId: The id of the user to get suggestions for. :param count: The amount of users to return. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = { "noUser": 0, "pageId": userId, "userId": userId, "userCount": count, "scene": 15, } api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = [] for x in self.getData(b, **kwargs)["body"][2]["exploreList"]: res.append(x["cardItem"]) return res[:count]
def getSuggestedMusicbyID( self, count=30, userId="6745191554350760966", **kwargs ) -> list: """Returns suggested music given a TikTok user. :param userId: The id of the user to get suggestions for. :param count: The amount of users to return. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) query = { "noUser": 0, "pageId": userId, "userId": userId, "userCount": count, "scene": 15, } api_url = "{}node/share/discover?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, **kwargs) res = [] for x in self.getData(b, proxy=proxy)["body"][2]["exploreList"]: res.append(x["cardItem"]) return res[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def getSuggestedMusicIDCrawler( self, count=30, startingId="6745191554350760966", **kwargs ) -> list: """Crawls for hashtags. :param count: The amount of users to crawl for. :param startingId: The ID of a TikTok user to start at. :param language: The language parameter. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) musics = [] ids = self.getSuggestedUsersbyIDCrawler( count=count, startingId=startingId, **kwargs ) while len(musics) < count and len(ids) != 0: userId = random.choice(ids) newTags = self.getSuggestedMusicbyID(userId=userId["id"], **kwargs) ids.remove(userId) for music in newTags: if music not in musics: musics.append(music) return musics[:count]
def getSuggestedMusicIDCrawler( self, count=30, startingId="6745191554350760966", **kwargs ) -> list: """Crawls for hashtags. :param count: The amount of users to crawl for. :param startingId: The ID of a TikTok user to start at. :param language: The language parameter. :param proxy: The IP address of a proxy to make requests from. """ ( region, language, proxy, maxCount, ) = self.__process_kwargs__(kwargs) musics = [] ids = self.getSuggestedUsersbyIDCrawler( count=count, startingId=startingId, language=language, proxy=proxy ) while len(musics) < count and len(ids) != 0: userId = random.choice(ids) newTags = self.getSuggestedMusicbyID( userId=userId["id"], language=language, proxy=proxy ) ids.remove(userId) for music in newTags: if music not in musics: musics.append(music) return musics[:count]
https://github.com/davidteather/TikTok-Api/issues/319
# Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\User\AppData\Local\Programs\Python\Python37\lib\site-packages\TikTokApi\tiktok.py", line 373, in byUsername **kwargs, TypeError: userPosts() got multiple values for keyword argument 'proxy'
TypeError
def trending(self, count=30, language="en", region="US", proxy=None) -> dict: """ Gets trending TikToks """ response = [] maxCount = 50 maxCursor = 0 first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": 1, "type": 5, "secUid": "", "maxCursor": maxCursor, "minCursor": 0, "sourceType": 12, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, language=language, proxy=proxy) res = self.getData(b, proxy=proxy) if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
def trending(self, count=30, language="en", region="US", proxy=None) -> dict: """ Gets trending TikToks """ response = [] maxCount = 50 maxCursor = 0 first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": 1, "type": 5, "secUid": "", "maxCursor": maxCursor, "minCursor": 0, "sourceType": 12, "appId": 1233, "region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, language=language, proxy=proxy) res = self.getData(b, proxy=proxy) if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: if self.debug: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
https://github.com/davidteather/TikTok-Api/issues/251
api.byHashtag('love') {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36', 'accept-encoding': 'gzip, deflate, br', 'accept': 'application/json, text/plain, */*', 'Connection': 'keep-alive', 'authority': 'm.tiktok.com', 'method': 'GET', 'path': '/share/item/list?aid=1988&amp;app_name=tiktok_web&amp;device_platform=web&amp;referer=&amp;user_agent=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML,+like+Gecko)+Chrome%2F84.0.4147.125+Safari%2F537.36&amp;cookie_enabled=true&amp;screen_width=2560&amp;screen_height=1440&amp;browser_language=&amp;browser_platform=&amp;browser_name=&amp;browser_version=&amp;browser_online=true&amp;timezone_name=&amp;priority_region=&amp;appId=1233&amp;appType=m&amp;isAndroid=false&amp;isMobile=false&amp;isIOS=false&amp;OS=windows&amp;did=822148675&amp;region=US&amp;secUid=&amp;id=4231&amp;type=3&amp;count=30&amp;minCursor=0&amp;maxCursor=0&amp;shareUid=&amp;recType=&amp;lang=en&amp;verifyFp=AaN99VturDQ2&amp;_signature=_02B4Z6wo00f01SDv8tgAAIBB6rMaD8GoX..ZAABdw74', 'scheme': 'https', 'accept-language': 'en-US,en;q=0.9', 'referrer': 'https://www.tiktok.com/', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-site'} Converting response to JSON failed response is below (probably empty) Traceback (most recent call last): File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 85, in getData return r.json() File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/requests/models.py", line 898, in json return complexjson.loads(self.text, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<input>", line 1, in <module> File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 357, in byHashtag res = self.getData(api_url, b, proxy=proxy, language=language) File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 91, in getData raise Exception('Invalid Response') Exception: Invalid Response
json.decoder.JSONDecodeError
def userPosts( self, userID, secUID, count=30, language="en", region="US", proxy=None ) -> dict: """Returns a dictionary listing TikToks given a user's ID and secUID :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ response = [] maxCount = 50 maxCursor = 0 first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": userID, "type": 1, "secUid": secUID, "maxCursor": maxCursor, "minCursor": 0, "sourceType": 8, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, proxy=proxy) res = self.getData(b, proxy=proxy) if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
def userPosts( self, userID, secUID, count=30, language="en", region="US", proxy=None ) -> dict: """Returns a dictionary listing TikToks given a user's ID and secUID :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ response = [] maxCount = 50 maxCursor = 0 first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": userID, "type": 1, "secUid": secUID, "maxCursor": maxCursor, "minCursor": 0, "sourceType": 8, "appId": 1233, "region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, proxy=proxy) res = self.getData(b, proxy=proxy) if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
https://github.com/davidteather/TikTok-Api/issues/251
api.byHashtag('love') {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36', 'accept-encoding': 'gzip, deflate, br', 'accept': 'application/json, text/plain, */*', 'Connection': 'keep-alive', 'authority': 'm.tiktok.com', 'method': 'GET', 'path': '/share/item/list?aid=1988&amp;app_name=tiktok_web&amp;device_platform=web&amp;referer=&amp;user_agent=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML,+like+Gecko)+Chrome%2F84.0.4147.125+Safari%2F537.36&amp;cookie_enabled=true&amp;screen_width=2560&amp;screen_height=1440&amp;browser_language=&amp;browser_platform=&amp;browser_name=&amp;browser_version=&amp;browser_online=true&amp;timezone_name=&amp;priority_region=&amp;appId=1233&amp;appType=m&amp;isAndroid=false&amp;isMobile=false&amp;isIOS=false&amp;OS=windows&amp;did=822148675&amp;region=US&amp;secUid=&amp;id=4231&amp;type=3&amp;count=30&amp;minCursor=0&amp;maxCursor=0&amp;shareUid=&amp;recType=&amp;lang=en&amp;verifyFp=AaN99VturDQ2&amp;_signature=_02B4Z6wo00f01SDv8tgAAIBB6rMaD8GoX..ZAABdw74', 'scheme': 'https', 'accept-language': 'en-US,en;q=0.9', 'referrer': 'https://www.tiktok.com/', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-site'} Converting response to JSON failed response is below (probably empty) Traceback (most recent call last): File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 85, in getData return r.json() File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/requests/models.py", line 898, in json return complexjson.loads(self.text, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<input>", line 1, in <module> File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 357, in byHashtag res = self.getData(api_url, b, proxy=proxy, language=language) File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 91, in getData raise Exception('Invalid Response') Exception: Invalid Response
json.decoder.JSONDecodeError
def userLiked( self, userID, secUID, count=30, language="en", region="US", proxy=None ) -> dict: """Returns a dictionary listing TikToks that a given a user has liked. Note: The user's likes must be public :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ response = [] maxCount = 50 maxCursor = 0 first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": userID, "type": 2, "secUid": secUID, "maxCursor": maxCursor, "minCursor": 0, "sourceType": 9, "appId": 1233, "region": region, "priority_region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, proxy=proxy) res = self.getData(b, proxy=proxy) try: res["items"] except Exception: if self.debug: print("Most Likely User's List is Empty") return [] if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
def userLiked( self, userID, secUID, count=30, language="en", region="US", proxy=None ) -> dict: """Returns a dictionary listing TikToks that a given a user has liked. Note: The user's likes must be public :param userID: The userID of the user, which TikTok assigns. :param secUID: The secUID of the user, which TikTok assigns. :param count: The number of posts to return. Note: seems to only support up to ~2,000 :param language: The 2 letter code of the language to return. Note: Doesn't seem to have an affect. :param region: The 2 letter region code. Note: Doesn't seem to have an affect. :param proxy: The IP address of a proxy to make requests from. """ response = [] maxCount = 50 maxCursor = 0 first = True while len(response) < count: if count < maxCount: realCount = count else: realCount = maxCount query = { "count": realCount, "id": userID, "type": 2, "secUid": secUID, "maxCursor": maxCursor, "minCursor": 0, "sourceType": 9, "appId": 1233, "region": region, "language": language, } api_url = "{}api/item_list/?{}&{}".format( BASE_URL, self.__add_new_params__(), urlencode(query) ) b = browser(api_url, proxy=proxy) res = self.getData(b, proxy=proxy) try: res["items"] except Exception: if self.debug: print("Most Likely User's List is Empty") return [] if "items" in res.keys(): for t in res["items"]: response.append(t) if not res["hasMore"] and not first: print("TikTok isn't sending more TikToks beyond this point.") return response realCount = count - len(response) maxCursor = res["maxCursor"] first = False return response[:count]
https://github.com/davidteather/TikTok-Api/issues/251
api.byHashtag('love') {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36', 'accept-encoding': 'gzip, deflate, br', 'accept': 'application/json, text/plain, */*', 'Connection': 'keep-alive', 'authority': 'm.tiktok.com', 'method': 'GET', 'path': '/share/item/list?aid=1988&amp;app_name=tiktok_web&amp;device_platform=web&amp;referer=&amp;user_agent=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML,+like+Gecko)+Chrome%2F84.0.4147.125+Safari%2F537.36&amp;cookie_enabled=true&amp;screen_width=2560&amp;screen_height=1440&amp;browser_language=&amp;browser_platform=&amp;browser_name=&amp;browser_version=&amp;browser_online=true&amp;timezone_name=&amp;priority_region=&amp;appId=1233&amp;appType=m&amp;isAndroid=false&amp;isMobile=false&amp;isIOS=false&amp;OS=windows&amp;did=822148675&amp;region=US&amp;secUid=&amp;id=4231&amp;type=3&amp;count=30&amp;minCursor=0&amp;maxCursor=0&amp;shareUid=&amp;recType=&amp;lang=en&amp;verifyFp=AaN99VturDQ2&amp;_signature=_02B4Z6wo00f01SDv8tgAAIBB6rMaD8GoX..ZAABdw74', 'scheme': 'https', 'accept-language': 'en-US,en;q=0.9', 'referrer': 'https://www.tiktok.com/', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-site'} Converting response to JSON failed response is below (probably empty) Traceback (most recent call last): File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 85, in getData return r.json() File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/requests/models.py", line 898, in json return complexjson.loads(self.text, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<input>", line 1, in <module> File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 357, in byHashtag res = self.getData(api_url, b, proxy=proxy, language=language) File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 91, in getData raise Exception('Invalid Response') Exception: Invalid Response
json.decoder.JSONDecodeError
def __add_new_params__(self) -> str: query = { "aid": 1988, "app_name": "tiktok_web", "device_platform": "web", "Referer": "", "user_agent": self.__format_new_params__(self.userAgent), "cookie_enabled": "true", "screen_width": self.width, "screen_height": self.height, "browser_language": self.browser_language, "browser_platform": self.browser_platform, "browser_name": self.browser_name, "browser_version": self.browser_version, "browser_online": "true", "ac": "4g", "timezone_name": self.timezone_name, "appId": 1233, "appType": "m", "isAndroid": False, "isMobile": False, "isIOS": False, "OS": "windows", } return urlencode(query)
def __add_new_params__(self) -> str: query = { "aid": 1988, "app_name": "tiktok_web", "device_platform": "web", "referer": "", "user_agent": self.__format_new_params__(self.userAgent), "cookie_enabled": "true", "screen_width": self.width, "screen_height": self.height, "browser_language": self.browser_language, "browser_platform": self.browser_platform, "browser_name": self.browser_name, "browser_version": self.browser_version, "browser_online": "true", "ac": "4g", "timezone_name": self.timezone_name, "priority_region": "", "appId": 1233, "appType": "m", "isAndroid": False, "isMobile": False, "isIOS": False, "OS": "windows", } return urlencode(query)
https://github.com/davidteather/TikTok-Api/issues/251
api.byHashtag('love') {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36', 'accept-encoding': 'gzip, deflate, br', 'accept': 'application/json, text/plain, */*', 'Connection': 'keep-alive', 'authority': 'm.tiktok.com', 'method': 'GET', 'path': '/share/item/list?aid=1988&amp;app_name=tiktok_web&amp;device_platform=web&amp;referer=&amp;user_agent=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML,+like+Gecko)+Chrome%2F84.0.4147.125+Safari%2F537.36&amp;cookie_enabled=true&amp;screen_width=2560&amp;screen_height=1440&amp;browser_language=&amp;browser_platform=&amp;browser_name=&amp;browser_version=&amp;browser_online=true&amp;timezone_name=&amp;priority_region=&amp;appId=1233&amp;appType=m&amp;isAndroid=false&amp;isMobile=false&amp;isIOS=false&amp;OS=windows&amp;did=822148675&amp;region=US&amp;secUid=&amp;id=4231&amp;type=3&amp;count=30&amp;minCursor=0&amp;maxCursor=0&amp;shareUid=&amp;recType=&amp;lang=en&amp;verifyFp=AaN99VturDQ2&amp;_signature=_02B4Z6wo00f01SDv8tgAAIBB6rMaD8GoX..ZAABdw74', 'scheme': 'https', 'accept-language': 'en-US,en;q=0.9', 'referrer': 'https://www.tiktok.com/', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-site'} Converting response to JSON failed response is below (probably empty) Traceback (most recent call last): File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 85, in getData return r.json() File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/requests/models.py", line 898, in json return complexjson.loads(self.text, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<input>", line 1, in <module> File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 357, in byHashtag res = self.getData(api_url, b, proxy=proxy, language=language) File "~/PycharmProjects/backup_scrapers/vevn/lib/python3.8/site-packages/TikTokApi/tiktok.py", line 91, in getData raise Exception('Invalid Response') Exception: Invalid Response
json.decoder.JSONDecodeError
def setup_rbac(self) -> None: """ Setup the client application for the OneFuzz instance. By default, Service Principals do not have access to create client applications in AAD. """ if self.results["client_id"] and self.results["client_secret"]: logger.info("using existing client application") return client = get_client_from_cli_profile(GraphRbacManagementClient) logger.info("checking if RBAC already exists") try: existing = list( client.applications.list( filter="displayName eq '%s'" % self.application_name ) ) except GraphErrorException: logger.error("unable to query RBAC. Provide client_id and client_secret") sys.exit(1) app_roles = [ AppRole( allowed_member_types=["Application"], display_name=OnefuzzAppRole.CliClient.value, id=str(uuid.uuid4()), is_enabled=True, description="Allows access from the CLI.", value=OnefuzzAppRole.CliClient.value, ), AppRole( allowed_member_types=["Application"], display_name=OnefuzzAppRole.ManagedNode.value, id=str(uuid.uuid4()), is_enabled=True, description="Allow access from a lab machine.", value=OnefuzzAppRole.ManagedNode.value, ), ] app: Optional[Application] = None if not existing: logger.info("creating Application registration") url = "https://%s.azurewebsites.net" % self.application_name params = ApplicationCreateParameters( display_name=self.application_name, identifier_uris=[url], reply_urls=[url + "/.auth/login/aad/callback"], optional_claims=OptionalClaims(id_token=[], access_token=[]), required_resource_access=[ RequiredResourceAccess( resource_access=[ ResourceAccess(id=USER_IMPERSONATION, type="Scope") ], resource_app_id="00000002-0000-0000-c000-000000000000", ) ], app_roles=app_roles, ) app = client.applications.create(params) logger.info("creating service principal") service_principal_params = ServicePrincipalCreateParameters( account_enabled=True, app_role_assignment_required=False, service_principal_type="Application", app_id=app.app_id, ) client.service_principals.create(service_principal_params) else: app = existing[0] existing_role_values = [app_role.value for app_role in app.app_roles] has_missing_roles = any( [role.value not in existing_role_values for role in app_roles] ) if has_missing_roles: # disabling the existing app role first to allow the update # this is a requirement to update the application roles for role in app.app_roles: role.is_enabled = False client.applications.patch( app.object_id, ApplicationUpdateParameters(app_roles=app.app_roles) ) # overriding the list of app roles client.applications.patch( app.object_id, ApplicationUpdateParameters(app_roles=app_roles) ) creds = list(client.applications.list_password_credentials(app.object_id)) client.applications.update_password_credentials(app.object_id, creds) (password_id, password) = self.create_password(app.object_id) cli_app = list(client.applications.list(filter="appId eq '%s'" % ONEFUZZ_CLI_APP)) if len(cli_app) == 0: logger.info( "Could not find the default CLI application under the current " "subscription, creating a new one" ) app_info = register_application( "onefuzz-cli", self.application_name, OnefuzzAppRole.CliClient ) self.cli_config = { "client_id": app_info.client_id, "authority": app_info.authority, } else: authorize_application(uuid.UUID(ONEFUZZ_CLI_APP), app.app_id) self.results["client_id"] = app.app_id self.results["client_secret"] = password # Log `client_secret` for consumption by CI. if self.log_service_principal: logger.info("client_id: %s client_secret: %s", app.app_id, password) else: logger.debug("client_id: %s client_secret: %s", app.app_id, password)
def setup_rbac(self) -> None: """ Setup the client application for the OneFuzz instance. By default, Service Principals do not have access to create client applications in AAD. """ if self.results["client_id"] and self.results["client_secret"]: logger.info("using existing client application") return client = get_client_from_cli_profile(GraphRbacManagementClient) logger.info("checking if RBAC already exists") try: existing = list( client.applications.list( filter="displayName eq '%s'" % self.application_name ) ) except GraphErrorException: logger.error("unable to query RBAC. Provide client_id and client_secret") sys.exit(1) app_roles = [ AppRole( allowed_member_types=["Application"], display_name=OnefuzzAppRole.CliClient.value, id=str(uuid.uuid4()), is_enabled=True, description="Allows access from the CLI.", value=OnefuzzAppRole.CliClient.value, ), AppRole( allowed_member_types=["Application"], display_name=OnefuzzAppRole.ManagedNode.value, id=str(uuid.uuid4()), is_enabled=True, description="Allow access from a lab machine.", value=OnefuzzAppRole.ManagedNode.value, ), ] app: Optional[Application] = None if not existing: logger.info("creating Application registration") url = "https://%s.azurewebsites.net" % self.application_name params = ApplicationCreateParameters( display_name=self.application_name, identifier_uris=[url], reply_urls=[url + "/.auth/login/aad/callback"], optional_claims=OptionalClaims(id_token=[], access_token=[]), required_resource_access=[ RequiredResourceAccess( resource_access=[ ResourceAccess(id=USER_IMPERSONATION, type="Scope") ], resource_app_id="00000002-0000-0000-c000-000000000000", ) ], app_roles=app_roles, ) app = client.applications.create(params) logger.info("creating service principal") service_principal_params = ServicePrincipalCreateParameters( account_enabled=True, app_role_assignment_required=False, service_principal_type="Application", app_id=app.app_id, ) client.service_principals.create(service_principal_params) else: app = existing[0] existing_role_values = [app_role.value for app_role in app.app_roles] has_missing_roles = any( [role.value not in existing_role_values for role in app_roles] ) if has_missing_roles: # disabling the existing app role first to allow the update # this is a requirement to update the application roles for role in app.app_roles: role.is_enabled = False client.applications.patch( app.object_id, ApplicationUpdateParameters(app_roles=app.app_roles) ) # overriding the list of app roles client.applications.patch( app.object_id, ApplicationUpdateParameters(app_roles=app_roles) ) creds = list(client.applications.list_password_credentials(app.object_id)) client.applications.update_password_credentials(app.object_id, creds) (password_id, password) = self.create_password(app.object_id) cli_app = client.applications.list(filter="appId eq '%s'" % ONEFUZZ_CLI_APP) onefuzz_cli_app_uuid = uuid.UUID(ONEFUZZ_CLI_APP) if not cli_app: logger.info( "Could not find the default CLI application under the current " "subscription, creating a new one" ) app_info = register_application( "onefuzz-cli", self.application_name, OnefuzzAppRole.CliClient ) self.cli_config = { "client_id": app_info.client_id, "authority": app_info.authority, } else: authorize_application(onefuzz_cli_app_uuid, app.app_id) self.results["client_id"] = app.app_id self.results["client_secret"] = password # Log `client_secret` for consumption by CI. if self.log_service_principal: logger.info("client_id: %s client_secret: %s", app.app_id, password) else: logger.debug("client_id: %s client_secret: %s", app.app_id, password)
https://github.com/microsoft/onefuzz/issues/486
(onefuzz) user@Azure:~/onefuzz$ python deploy.py northeurope user_group <redacted>-onefuzz <redacted>@....com INFO:deploy:checking if RBAC already exists INFO:deploy:creating Application registration INFO:deploy:creating service principal Traceback (most recent call last): File "deploy.py", line 902, in <module> main() File "deploy.py", line 896, in main state[1](client) File "deploy.py", line 349, in setup_rbac authorize_application(onefuzz_cli_app_uuid, app.app_id) File "/home/user/onefuzz/registration.py", line 340, in authorize_application "preAuthorizedApplications": preAuthorizedApplications.to_list() File "/home/user/onefuzz/registration.py", line 79, in query_microsoft_graph response.status_code, registration.GraphQueryError: request did not succeed: HTTP 400 - { "error": { "code": "InvalidAppId", "message": "Property PreAuthorizedApplication references applications 72f1562a-8c0c-41ea-beb9-fa2b71c80134 that cannot be found.", "innerError": { "date": "2021-01-29T16:24:51", "request-id": "9253d1ee-4992-4a39-8c22-6add7ff311eb", "client-request-id": "9253d1ee-4992-4a39-8c22-6add7ff311eb" }, "details": [ { "target": "api.preAuthorizedApplications.appId", "code": "InvalidValue" } ] } }
registration.GraphQueryError
def top(opts): if not ENABLED: raise Exception("Could not import tracemalloc") lines = opts.lines seconds = opts.seconds force_start = opts.force_start if opts.socket is None: socket = ipc.find_sockfile() else: socket = opts.socket client = ipc.Client(socket) client = command_interface.IPCCommandInterface(client) client = command_client.InteractiveCommandClient(client) try: if not opts.raw: curses.wrapper( get_stats, client, limit=lines, seconds=seconds, force_start=force_start ) else: raw_stats(client, limit=lines, force_start=force_start) except TraceNotStarted: print( "tracemalloc not started on qtile, start by setting " "PYTHONTRACEMALLOC=1 before starting qtile" ) print("or force start tracemalloc now, but you'll lose early traces") exit(1) except TraceCantStart: print("Can't start tracemalloc on qtile, check the logs") except KeyboardInterrupt: exit(-1) except curses.error: print("Terminal too small for curses interface.") raw_stats(client, limit=lines, force_start=force_start)
def top(opts): if not ENABLED: raise Exception("Could not import tracemalloc") lines = opts.lines seconds = opts.seconds force_start = opts.force_start if opts.socket is None: socket = ipc.find_sockfile() else: socket = opts.socket client = ipc.Client(socket) client = command_interface.IPCCommandInterface(client) client = command_client.InteractiveCommandClient(client) try: if not opts.raw: curses.wrapper( get_stats, client, limit=lines, seconds=seconds, force_start=force_start ) else: raw_stats(client, limit=lines, force_start=force_start) except TraceNotStarted: print( "tracemalloc not started on qtile, start by setting " "PYTHONTRACEMALLOC=1 before starting qtile" ) print("or force start tracemalloc now, but you'll lose early traces") exit(1) except TraceCantStart: print("Can't start tracemalloc on qtile, check the logs") except KeyboardInterrupt: exit(-1)
https://github.com/qtile/qtile/issues/2032
$ qtile top --force-start $ qtile top Traceback (most recent call last): File "libqtile/scripts/main.py", line 46, in main options.func(options) File "qtile/libqtile/scripts/top.py", line 158, in top force_start=force_start) File "/usr/lib/python3.7/curses/__init__.py", line 102, in wrapper return func(stdscr, *args, **kwds) File "libqtile/scripts/top.py", line 95, in get_stats scr.addstr(cnt + 1, 0, '{:<3} {:<40} {:<30}'.format(index, filename, mem)) _curses.error: addwstr() returned ERR
_curses.error
def restart(self): argv = [sys.executable] + sys.argv if "--no-spawn" not in argv: argv.append("--no-spawn") state_file = os.path.join(tempfile.gettempdir(), "qtile-state") try: with open(state_file, "wb") as f: pickle.dump(QtileState(self), f, protocol=0) except: # noqa: E722 logger.error("Unable to pickle qtile state") argv = [s for s in argv if not s.startswith("--with-state")] argv.append("--with-state=" + state_file) self._restart = (sys.executable, argv) self.stop()
def restart(self): argv = [sys.executable] + sys.argv if "--no-spawn" not in argv: argv.append("--no-spawn") buf = io.BytesIO() try: pickle.dump(QtileState(self), buf, protocol=0) except: # noqa: E722 logger.error("Unable to pickle qtile state") argv = [s for s in argv if not s.startswith("--with-state")] argv.append("--with-state=" + buf.getvalue().decode()) self._restart = (sys.executable, argv) self.stop()
https://github.com/qtile/qtile/issues/1888
2020-08-29 02:09:05,707 ERROR libqtile manager.py:process_key_event():L374 KB command error restart: Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/libqtile/command_interface.py", line 312, in call return SUCCESS, cmd(*args, **kwargs) File "/usr/lib/python3.8/site-packages/libqtile/core/manager.py", line 1147, in cmd_restart self.restart() File "/usr/lib/python3.8/site-packages/libqtile/core/manager.py", line 290, in restart argv.append('--with-state=' + buf.getvalue().decode()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 163: invalid continuation byte
UnicodeDecodeError
def cmd_get_state(self): """Get pickled state for restarting qtile""" buf = io.BytesIO() pickle.dump(QtileState(self), buf, protocol=0) state = buf.getvalue().decode(errors="backslashreplace") logger.debug("State = ") logger.debug("".join(state.split("\n"))) return state
def cmd_get_state(self): """Get pickled state for restarting qtile""" buf = io.BytesIO() pickle.dump(QtileState(self), buf, protocol=0) state = buf.getvalue().decode() logger.debug("State = ") logger.debug("".join(state.split("\n"))) return state
https://github.com/qtile/qtile/issues/1888
2020-08-29 02:09:05,707 ERROR libqtile manager.py:process_key_event():L374 KB command error restart: Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/libqtile/command_interface.py", line 312, in call return SUCCESS, cmd(*args, **kwargs) File "/usr/lib/python3.8/site-packages/libqtile/core/manager.py", line 1147, in cmd_restart self.restart() File "/usr/lib/python3.8/site-packages/libqtile/core/manager.py", line 290, in restart argv.append('--with-state=' + buf.getvalue().decode()) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 163: invalid continuation byte
UnicodeDecodeError
def __init__(self, **config): base.InLoopPollText.__init__(self, **config) self.add_defaults(Backlight.defaults) self._future = None self.brightness_file = os.path.join( BACKLIGHT_DIR, self.backlight_name, self.brightness_file, ) self.max_brightness_file = os.path.join( BACKLIGHT_DIR, self.backlight_name, self.max_brightness_file, ) mouse_callbacks = { "Button4": lambda q: self.cmd_change_backlight(ChangeDirection.UP), "Button5": lambda q: self.cmd_change_backlight(ChangeDirection.DOWN), } mouse_callbacks.update(self.mouse_callbacks) self.mouse_callbacks = mouse_callbacks
def __init__(self, **config): base.InLoopPollText.__init__(self, **config) self.add_defaults(Backlight.defaults) self.future = None self.brightness_file = os.path.join( BACKLIGHT_DIR, self.backlight_name, self.brightness_file, ) self.max_brightness_file = os.path.join( BACKLIGHT_DIR, self.backlight_name, self.max_brightness_file, ) self.max_value = self._load_file(self.max_brightness_file) self.step = self.max_value * self.step / 100
https://github.com/qtile/qtile/issues/1866
Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/libqtile/confreader.py", line 92, in load config = __import__(name) # noqa: F811 File "/home/neworld/.config/qtile/config.py", line 363, in <module> widget.Backlight( File "/usr/lib/python3.8/site-packages/libqtile/utils.py", line 213, in class_proxy return cls(*args, **kwargs) File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 96, in __init__ self.max_value = self._load_file(self.max_brightness_file) File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 105, in _load_file raise RuntimeError( RuntimeError: Unable to read status for max_brightness
RuntimeError
def _get_info(self): brightness = self._load_file(self.brightness_file) max_value = self._load_file(self.max_brightness_file) return brightness / max_value
def _get_info(self): brightness = self._load_file(self.brightness_file) info = { "brightness": brightness, "max": self.max_value, } return info
https://github.com/qtile/qtile/issues/1866
Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/libqtile/confreader.py", line 92, in load config = __import__(name) # noqa: F811 File "/home/neworld/.config/qtile/config.py", line 363, in <module> widget.Backlight( File "/usr/lib/python3.8/site-packages/libqtile/utils.py", line 213, in class_proxy return cls(*args, **kwargs) File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 96, in __init__ self.max_value = self._load_file(self.max_brightness_file) File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 105, in _load_file raise RuntimeError( RuntimeError: Unable to read status for max_brightness
RuntimeError
def poll(self): try: percent = self._get_info() except RuntimeError as e: return "Error: {}".format(e) return self.format.format(percent=percent)
def poll(self): try: info = self._get_info() except RuntimeError as e: return "Error: {}".format(e) percent = info["brightness"] / info["max"] return self.format.format(percent=percent)
https://github.com/qtile/qtile/issues/1866
Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/libqtile/confreader.py", line 92, in load config = __import__(name) # noqa: F811 File "/home/neworld/.config/qtile/config.py", line 363, in <module> widget.Backlight( File "/usr/lib/python3.8/site-packages/libqtile/utils.py", line 213, in class_proxy return cls(*args, **kwargs) File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 96, in __init__ self.max_value = self._load_file(self.max_brightness_file) File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 105, in _load_file raise RuntimeError( RuntimeError: Unable to read status for max_brightness
RuntimeError
def cmd_change_backlight(self, direction): if self._future and not self._future.done(): return new = now = self._get_info() * 100 if direction is ChangeDirection.DOWN: new = max(now - self.step, 0) elif direction is ChangeDirection.UP: new = min(now + self.step, 100) if new != now: self._future = self.qtile.run_in_executor(self._change_backlight, new)
def cmd_change_backlight(self, direction): if self.future and not self.future.done(): return info = self._get_info() if not info: new = now = self.max_value else: new = now = info["brightness"] if direction is ChangeDirection.DOWN: # down new = max(now - self.step, 0) elif direction is ChangeDirection.UP: # up new = min(now + self.step, self.max_value) if new != now: self.future = self.qtile.run_in_executor(self.change_backlight, new)
https://github.com/qtile/qtile/issues/1866
Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/libqtile/confreader.py", line 92, in load config = __import__(name) # noqa: F811 File "/home/neworld/.config/qtile/config.py", line 363, in <module> widget.Backlight( File "/usr/lib/python3.8/site-packages/libqtile/utils.py", line 213, in class_proxy return cls(*args, **kwargs) File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 96, in __init__ self.max_value = self._load_file(self.max_brightness_file) File "/usr/lib/python3.8/site-packages/libqtile/widget/backlight.py", line 105, in _load_file raise RuntimeError( RuntimeError: Unable to read status for max_brightness
RuntimeError
def when(self, layout=None, when_floating=True): self._layout = layout self._when_floating = when_floating return self
def when(self, layout=None, when_floating=True): self._layout = layout self._when_floating = when_floating
https://github.com/qtile/qtile/issues/1629
libqtile xcore.py:_xpoll():L277 Got an exception in poll loop Traceback (most recent call last): File "/share/git/qtile/libqtile/backend/x11/xcore.py", line 246, in _xpoll ret = target(event) File "/share/git/qtile/libqtile/backend/x11/xcore.py", line 494, in handle_KeyPress self.qtile.process_key_event(keysym, event.state &amp; self._valid_mask) File "/share/git/qtile/libqtile/core/manager.py", line 342, in process_key_event if cmd.check(self): AttributeError: 'NoneType' object has no attribute 'check'
AttributeError
def _get_time(self): time.tzset() if six.PY3: now = datetime.now(timezone.utc).astimezone() else: now = datetime.now() return (now + self.DELTA).strftime(self.format)
def _get_time(self): time.tzset() now = datetime.now(utc).astimezone() return (now + self.DELTA).strftime(self.format)
https://github.com/qtile/qtile/issues/1258
Traceback (most recent call last): File "/nix/store/vws161bihzlcxbiq17h63wdcdg12vrsc-python2.7-trollius-2.2/lib/python2.7/site-packages/trollius/events.py", line 136, in _run self._callback(*self._args) File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/manager.py", line 1197, in f func(*args) File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/widget/base.py", line 428, in timer_setup update_interval = self.tick() File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/widget/clock.py", line 76, in tick self.update(self.poll()) File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/widget/clock.py", line 91, in poll return self._get_time() File "/nix/store/mpi5ibr3xajzqqsaiyb885pywl269bg9-qtile-0.13.0/lib/python2.7/site-packages/libqtile/widget/clock.py", line 83, in _get_time now = datetime.now(utc).astimezone() TypeError: Required argument 'tz' (pos 1) not found
TypeError
def draw(self): self.drawer.clear(self.background or self.bar.background) offset = 0 for i, g in enumerate(self.groups): is_block = self.highlight_method == "block" is_line = self.highlight_method == "line" if not is_line: highlight_color = None bw = self.box_width([g]) if self.group_has_urgent(g) and self.urgent_alert_method == "text": text_color = self.urgent_text elif g.windows: text_color = self.active else: text_color = self.inactive if g.screen: if self.highlight_method == "text": border = self.bar.background text_color = self.this_current_screen_border else: if self.bar.screen.group.name == g.name: if self.qtile.currentScreen == self.bar.screen: border = self.this_current_screen_border highlight_color = self.highlight_color else: border = self.this_screen_border highlight_color = self.bar.background else: border = self.other_screen_border highlight_color = self.bar.background elif self.group_has_urgent(g) and self.urgent_alert_method in ( "border", "block", "line", ): border = self.urgent_border highlight_color = self.bar.background if self.urgent_alert_method == "block": is_block = True elif self.urgent_alert_method == "line": is_line = True else: border = self.background or self.bar.background highlight_color = self.bar.background self.drawbox( self.margin_x + offset, g.name, border, text_color, highlight_color, self.line_thickness, self.rounded, is_block, bw - self.margin_x * 2 - self.padding_x * 2, is_line, ) offset += bw self.drawer.draw(offsetx=self.offset, width=self.width)
def draw(self): self.drawer.clear(self.background or self.bar.background) offset = 0 for i, g in enumerate(self.groups): is_block = self.highlight_method == "block" is_line = self.highlight_method == "line" if not is_line: highlight_color = None bw = self.box_width([g]) if self.group_has_urgent(g) and self.urgent_alert_method == "text": text_color = self.urgent_text elif g.windows: text_color = self.active else: text_color = self.inactive if g.screen: if self.highlight_method == "text": border = self.bar.background text_color = self.this_current_screen_border else: if self.bar.screen.group.name == g.name: if self.qtile.currentScreen == self.bar.screen: border = self.this_current_screen_border highlight_color = self.highlight_color else: border = self.this_screen_border highlight_color = self.bar.background else: border = self.other_screen_border elif self.group_has_urgent(g) and self.urgent_alert_method in ( "border", "block", ): border = self.urgent_border if self.urgent_alert_method == "block": is_block = True else: border = self.background or self.bar.background highlight_color = self.bar.background self.drawbox( self.margin_x + offset, g.name, border, text_color, highlight_color, self.line_thickness, self.rounded, is_block, bw - self.margin_x * 2 - self.padding_x * 2, is_line, ) offset += bw self.drawer.draw(offsetx=self.offset, width=self.width)
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def framed(self, border_width, border_color, pad_x, pad_y, highlight_color=None): return TextFrame( self, border_width, border_color, pad_x, pad_y, highlight_color=highlight_color )
def framed( self, border_width, border_color, pad_x, pad_y, highlight_color=None, line_thickness=None, ): return TextFrame( self, border_width, border_color, pad_x, pad_y, highlight_color, line_thickness )
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def __init__( self, layout, border_width, border_color, pad_x, pad_y, highlight_color=None ): self.layout = layout self.border_width = border_width self.border_color = border_color self.drawer = self.layout.drawer self.highlight_color = highlight_color if isinstance(pad_x, collections.Iterable): self.pad_left = pad_x[0] self.pad_right = pad_x[1] else: self.pad_left = self.pad_right = pad_x if isinstance(pad_y, collections.Iterable): self.pad_top = pad_y[0] self.pad_bottom = pad_y[1] else: self.pad_top = self.pad_bottom = pad_y
def __init__( self, layout, border_width, border_color, pad_x, pad_y, highlight_color, line_thickness, ): self.layout = layout self.border_width = border_width self.border_color = border_color self.drawer = self.layout.drawer self.highlight_color = highlight_color self.line_thickness = line_thickness if isinstance(pad_x, collections.Iterable): self.pad_left = pad_x[0] self.pad_right = pad_x[1] else: self.pad_left = self.pad_right = pad_x if isinstance(pad_y, collections.Iterable): self.pad_top = pad_y[0] self.pad_bottom = pad_y[1] else: self.pad_top = self.pad_bottom = pad_y
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def draw(self, x, y, rounded=True, fill=False, line=False, highlight=False): self.drawer.set_source_rgb(self.border_color) opts = [ x, y, self.layout.width + self.pad_left + self.pad_right, self.layout.height + self.pad_top + self.pad_bottom, self.border_width, ] if line: if highlight: self.drawer.set_source_rgb(self.highlight_color) self.drawer.fillrect(*opts) self.drawer.set_source_rgb(self.border_color) # change to only fill in bottom line opts[1] = self.height - self.border_width # y opts[3] = self.border_width # height self.drawer.fillrect(*opts) elif fill: if rounded: self.drawer.rounded_fillrect(*opts) else: self.drawer.fillrect(*opts) else: if rounded: self.drawer.rounded_rectangle(*opts) else: self.drawer.rectangle(*opts) self.drawer.ctx.stroke() self.layout.draw(x + self.pad_left, y + self.pad_top)
def draw(self, x, y, bar_height=None, rounded=True, fill=False, line=False): self.drawer.set_source_rgb(self.border_color) opts = [ x, y, self.layout.width + self.pad_left + self.pad_right, self.layout.height + self.pad_top + self.pad_bottom, self.border_width, ] if line: if not bar_height: bar_height = self.layout.height + self.pad_top + self.pad_bottom highlight_opts = [ x, 0, self.layout.width + self.pad_left + self.pad_right, bar_height, self.border_width, ] self.drawer.set_source_rgb(self.highlight_color) self.drawer.fillrect(*highlight_opts) lineopts = [ x, bar_height - self.line_thickness, self.layout.width + self.pad_left + self.pad_right, self.line_thickness, self.border_width, ] self.drawer.set_source_rgb(self.border_color) self.drawer.fillrect(*lineopts) elif fill: if rounded: self.drawer.rounded_fillrect(*opts) else: self.drawer.fillrect(*opts) else: if rounded: self.drawer.rounded_rectangle(*opts) else: self.drawer.rectangle(*opts) self.drawer.ctx.stroke() self.layout.draw(x + self.pad_left, y + self.pad_top)
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def draw_fill(self, x, y, rounded=True): self.draw(x, y, rounded=rounded, fill=True)
def draw_fill(self, x, y, rounded=True): self.draw(x, y, rounded, fill=True)
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def draw_line(self, x, y, highlighted): self.draw(x, y, line=True, highlight=highlighted)
def draw_line(self, x, y, bar_height, rounded=False): self.draw(x, y, bar_height, rounded, line=True)
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def drawbox( self, offset, text, bordercolor, textcolor, width=None, rounded=False, block=False, line=False, highlighted=False, ): self.layout.text = text self.layout.font_family = self.font self.layout.font_size = self.fontsize self.layout.colour = textcolor if width is not None: self.layout.width = width if line: pad_y = (self.bar.height - self.layout.height) / 2 else: pad_y = self.padding_y framed = self.layout.framed( self.borderwidth, bordercolor, self.padding_x, pad_y, self.highlight_color ) y = self.margin_y if self.center_aligned: for t in base.MarginMixin.defaults: if t[0] == "margin": y += (self.bar.height - framed.height) / 2 - t[1] break if block: framed.draw_fill(offset, y, rounded) elif line: framed.draw_line(offset, y, highlighted) else: framed.draw(offset, y, rounded)
def drawbox( self, offset, text, bordercolor, textcolor, highlight_color, line_thickness, rounded=False, block=False, width=None, line=False, ): self.layout.text = text self.layout.font_family = self.font self.layout.font_size = self.fontsize self.layout.colour = textcolor if width is not None: self.layout.width = width framed = self.layout.framed( self.borderwidth, bordercolor, self.padding_x, self.padding_y, highlight_color, line_thickness, ) y = self.margin_y if self.center_aligned: for t in base.MarginMixin.defaults: if t[0] == "margin": y += (self.bar.height - framed.height) / 2 - t[1] break if block: framed.draw_fill(offset, y, rounded) elif line: framed.draw_line(offset, y, self.bar.size, rounded) else: framed.draw(offset, y, rounded)
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def draw(self): self.drawer.clear(self.background or self.bar.background) offset = 0 for i, g in enumerate(self.groups): to_highlight = False is_block = self.highlight_method == "block" is_line = self.highlight_method == "line" bw = self.box_width([g]) if self.group_has_urgent(g) and self.urgent_alert_method == "text": text_color = self.urgent_text elif g.windows: text_color = self.active else: text_color = self.inactive if g.screen: if self.highlight_method == "text": border = self.bar.background text_color = self.this_current_screen_border else: if self.bar.screen.group.name == g.name: if self.qtile.currentScreen == self.bar.screen: border = self.this_current_screen_border to_highlight = True else: border = self.this_screen_border else: border = self.other_screen_border elif self.group_has_urgent(g) and self.urgent_alert_method in ( "border", "block", "line", ): border = self.urgent_border if self.urgent_alert_method == "block": is_block = True elif self.urgent_alert_method == "line": is_line = True else: border = self.background or self.bar.background self.drawbox( self.margin_x + offset, g.name, border, text_color, width=bw - self.margin_x * 2 - self.padding_x * 2, rounded=self.rounded, block=is_block, line=is_line, highlighted=to_highlight, ) offset += bw self.drawer.draw(offsetx=self.offset, width=self.width)
def draw(self): self.drawer.clear(self.background or self.bar.background) offset = 0 for i, g in enumerate(self.groups): is_block = self.highlight_method == "block" is_line = self.highlight_method == "line" if not is_line: highlight_color = None bw = self.box_width([g]) if self.group_has_urgent(g) and self.urgent_alert_method == "text": text_color = self.urgent_text elif g.windows: text_color = self.active else: text_color = self.inactive if g.screen: if self.highlight_method == "text": border = self.bar.background text_color = self.this_current_screen_border else: if self.bar.screen.group.name == g.name: if self.qtile.currentScreen == self.bar.screen: border = self.this_current_screen_border highlight_color = self.highlight_color else: border = self.this_screen_border highlight_color = self.bar.background else: border = self.other_screen_border highlight_color = self.bar.background elif self.group_has_urgent(g) and self.urgent_alert_method in ( "border", "block", "line", ): border = self.urgent_border highlight_color = self.bar.background if self.urgent_alert_method == "block": is_block = True elif self.urgent_alert_method == "line": is_line = True else: border = self.background or self.bar.background highlight_color = self.bar.background self.drawbox( self.margin_x + offset, g.name, border, text_color, highlight_color, self.line_thickness, self.rounded, is_block, bw - self.margin_x * 2 - self.padding_x * 2, is_line, ) offset += bw self.drawer.draw(offsetx=self.offset, width=self.width)
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def drawbox( self, offset, text, bordercolor, textcolor, width=None, rounded=False, block=False, icon=None, ): self.drawtext(text, textcolor, width) icon_padding = (self.icon_size + 4) if icon else 0 padding_x = [self.padding_x + icon_padding, self.padding_x] framed = self.layout.framed( self.borderwidth, bordercolor, padding_x, self.padding_y ) if block: framed.draw_fill(offset, self.margin_y, rounded) else: framed.draw(offset, self.margin_y, rounded) if icon: self.draw_icon(icon, offset)
def drawbox( self, offset, text, bordercolor, textcolor, rounded=False, block=False, width=None, icon=None, ): self.drawtext(text, textcolor, width) icon_padding = (self.icon_size + 4) if icon else 0 padding_x = [self.padding_x + icon_padding, self.padding_x] framed = self.layout.framed( self.borderwidth, bordercolor, padding_x, self.padding_y ) if block: framed.draw_fill(offset, self.margin_y, rounded) else: framed.draw(offset, self.margin_y, rounded) if icon: self.draw_icon(icon, offset)
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def draw(self): self.drawer.clear(self.background or self.bar.background) offset = 0 for w in self.bar.screen.group.windows: state = "" if w is None: pass elif w.maximized: state = "[] " elif w.minimized: state = "_ " elif w.floating: state = "V " task = "%s%s" % (state, w.name if w and w.name else " ") if w.urgent: border = self.urgent_border elif w is w.group.currentWindow: border = self.border else: border = self.background or self.bar.background bw = self.box_width(task) self.drawbox( self.margin_x + offset, task, border, self.foreground, rounded=self.rounded, block=(self.highlight_method == "block"), width=(bw - self.margin_x * 2 - self.padding_x * 2), icon=self.get_window_icon(w), ) offset += bw + self.icon_size self.drawer.draw(offsetx=self.offset, width=self.width)
def draw(self): self.drawer.clear(self.background or self.bar.background) offset = 0 for w in self.bar.screen.group.windows: state = "" if w is None: pass elif w.maximized: state = "[] " elif w.minimized: state = "_ " elif w.floating: state = "V " task = "%s%s" % (state, w.name if w and w.name else " ") if w.urgent: border = self.urgent_border elif w is w.group.currentWindow: border = self.border else: border = self.background or self.bar.background bw = self.box_width(task) self.drawbox( self.margin_x + offset, task, border, self.foreground, self.rounded, self.highlight_method == "block", bw - self.margin_x * 2 - self.padding_x * 2, icon=self.get_window_icon(w), ) offset += bw + self.icon_size self.drawer.draw(offsetx=self.offset, width=self.width)
https://github.com/qtile/qtile/issues/790
Traceback (most recent call last): File "/usr/lib64/python3.4/asyncio/events.py", line 120, in _run self._callback(*self._args) File "/usr/lib64/python3.4/site-packages/libqtile/manager.py", line 1156, in f func(*args) File "/usr/lib64/python3.4/site-packages/libqtile/bar.py", line 288, in _actual_draw i.draw() File "/usr/lib64/python3.4/site-packages/libqtile/widget/groupbox.py", line 318, in draw highlight_color, UnboundLocalError: local variable 'highlight_color' referenced before assignment
UnboundLocalError
def alloc_color(self, color): """ Flexible color allocation. """ try: return self.conn.conn.core.AllocNamedColor(self.cid, len(color), color).reply() except xcffib.xproto.NameError: def x8to16(i): return 0xFFFF * (i & 0xFF) // 0xFF r = x8to16(int(color[-6] + color[-5], 16)) g = x8to16(int(color[-4] + color[-3], 16)) b = x8to16(int(color[-2] + color[-1], 16)) return self.conn.conn.core.AllocColor(self.cid, r, g, b).reply()
def alloc_color(self, color): """ Flexible color allocation. """ if color.startswith("#"): if len(color) != 7: raise ValueError("Invalid color: %s" % color) def x8to16(i): return 0xFFFF * (i & 0xFF) // 0xFF r = x8to16(int(color[1] + color[2], 16)) g = x8to16(int(color[3] + color[4], 16)) b = x8to16(int(color[5] + color[6], 16)) return self.conn.conn.core.AllocColor(self.cid, r, g, b).reply() else: return self.conn.conn.core.AllocNamedColor(self.cid, len(color), color).reply()
https://github.com/qtile/qtile/issues/394
Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/libqtile/manager.py", line 585, in _xpoll r = h(e) File "/usr/lib/python2.7/dist-packages/libqtile/manager.py", line 892, in handle_UnmapNotify self.unmanage(e.window) File "/usr/lib/python2.7/dist-packages/libqtile/manager.py", line 406, in unmanage c.group.remove(c) File "/usr/lib/python2.7/dist-packages/libqtile/group.py", line 215, in remove self.focus(nextfocus, True) File "/usr/lib/python2.7/dist-packages/libqtile/group.py", line 156, in focus l.focus(win) File "/usr/lib/python2.7/dist-packages/libqtile/layout/max.py", line 46, in focus self.group.layoutAll() File "/usr/lib/python2.7/dist-packages/libqtile/group.py", line 92, in layoutAll self.layout.layout(normal, screen) File "/usr/lib/python2.7/dist-packages/libqtile/layout/base.py", line 54, in layout self.configure(i, screen) File "/usr/lib/python2.7/dist-packages/libqtile/layout/tile.py", line 189, in configure bc = self.group.qtile.colorPixel(self.border_focus) File "/usr/lib/python2.7/dist-packages/libqtile/utils.py", line 99, in wrap ret = f(self, *args) File "/usr/lib/python2.7/dist-packages/libqtile/manager.py", line 364, in colorPixel return self.conn.screens[0].default_colormap.alloc_color(name).pixel File "/usr/lib/python2.7/dist-packages/libqtile/xcbq.py", line 288, in alloc_color self.cid, len(color), color BadName: <xcb.xproto.NameError object at 0x319c908>
xcb.xproto.NameError
def _receive(self): c = self.subclient ret = [] try: ret.append(self._receive_one(c)) except Empty: pass while c.connection is not None and c.connection.can_read(timeout=0): ret.append(self._receive_one(c)) return any(ret)
def _receive(self): c = self.subclient ret = [] try: ret.append(self._receive_one(c)) except Empty: pass if c.connection is not None: while c.connection.can_read(timeout=0): ret.append(self._receive_one(c)) return any(ret)
https://github.com/celery/kombu/issues/659
Traceback (most recent call last): File "/venv/lib/python3.4/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/venv/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/venv/lib/python3.4/site-packages/celery/bootsteps.py", line 370, in start return self.obj.start() File "/venv/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File "/venv/lib/python3.4/site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File "/venv/lib/python3.4/site-packages/celery/worker/consumer/consumer.py", line 584, in start c.loop(*c.loop_args()) File "/venv/lib/python3.4/site-packages/celery/worker/loops.py", line 88, in asynloop next(loop) File "/venv/lib/python3.4/site-packages/kombu/async/hub.py", line 345, in create_loop cb(*cbargs) File "/venv/lib/python3.4/site-packages/kombu/transport/redis.py", line 1038, in on_readable self.cycle.on_readable(fileno) File "/venv/lib/python3.4/site-packages/kombu/transport/redis.py", line 337, in on_readable chan.handlers[type]() File "/venv/lib/python3.4/site-packages/kombu/transport/redis.py", line 670, in _receive while c.connection.can_read(timeout=0): AttributeError: 'NoneType' object has no attribute 'can_read'
AttributeError
def _shrink_down(self, collect=True): class Noop: def __enter__(self): pass def __exit__(self, type, value, traceback): pass resource = self._resource # Items to the left are last recently used, so we remove those first. with getattr(resource, "mutex", Noop()): while len(resource.queue) > self.limit: R = resource.queue.popleft() if collect: self.collect_resource(R)
def _shrink_down(self, collect=True): resource = self._resource # Items to the left are last recently used, so we remove those first. with resource.mutex: while len(resource.queue) > self.limit: R = resource.queue.popleft() if collect: self.collect_resource(R)
https://github.com/celery/kombu/issues/741
Traceback (most recent call last): File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/gunicorn/workers/async.py", line 56, in handle self.handle_request(listener_name, req, client, addr) File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/gunicorn/workers/async.py", line 107, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/home/fga/workspace/kombu_eventlet_bug/wsgi.py", line 18, in app add.delay(1,2) File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/task.py", line 412, in delay return self.apply_async(args, kwargs) File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/task.py", line 535, in apply_async **options File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/base.py", line 734, in send_task with self.producer_or_acquire(producer) as P: File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/base.py", line 863, in producer_or_acquire producer, self.producer_pool.acquire, block=True, File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/base.py", line 1232, in producer_pool return self.amqp.producer_pool File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/amqp.py", line 610, in producer_pool self._producer_pool.limit = self.app.pool.limit File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/celery/app/base.py", line 1147, in pool pools.set_limit(limit) File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/kombu/pools.py", line 137, in set_limit pool.resize(limit) File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/kombu/resource.py", line 188, in resize self._shrink_down() File "/home/fga/workspace/kombu_eventlet_bug/.virtualenv/lib/python3.4/site-packages/kombu/resource.py", line 193, in _shrink_down with resource.mutex: AttributeError: 'LifoQueue' object has no attribute 'mutex'
AttributeError
def __lt__(self, other): """Implement the less-than operand.""" if hasattr(other, "alphabet"): if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]): warnings.warn( "Incompatible alphabets {0!r} and {1!r}".format( self.alphabet, other.alphabet ), BiopythonWarning, ) if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)): return str(self) < str(other) raise TypeError( "'<' not supported between instances of '{}' and '{}'".format( type(self).__name__, type(other).__name__ ) )
def __lt__(self, other): """Implement the less-than operand.""" if hasattr(other, "alphabet"): if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]): warnings.warn( "Incompatible alphabets {0!r} and {1!r}".format( self.alphabet, other.alphabet ), BiopythonWarning, ) return str(self) < str(other)
https://github.com/biopython/biopython/issues/1750
from Bio.Seq import Seq 'A' > Seq('A') False Seq('A') > 'A' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '>' not supported between instances of 'Seq' and 'str'
TypeError
def __le__(self, other): """Implement the less-than or equal operand.""" if hasattr(other, "alphabet"): if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]): warnings.warn( "Incompatible alphabets {0!r} and {1!r}".format( self.alphabet, other.alphabet ), BiopythonWarning, ) if isinstance(other, (str, Seq, MutableSeq, UnknownSeq)): return str(self) <= str(other) raise TypeError( "'<=' not supported between instances of '{}' and '{}'".format( type(self).__name__, type(other).__name__ ) )
def __le__(self, other): """Implement the less-than or equal operand.""" if hasattr(other, "alphabet"): if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]): warnings.warn( "Incompatible alphabets {0!r} and {1!r}".format( self.alphabet, other.alphabet ), BiopythonWarning, ) return str(self) <= str(other)
https://github.com/biopython/biopython/issues/1750
from Bio.Seq import Seq 'A' > Seq('A') False Seq('A') > 'A' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '>' not supported between instances of 'Seq' and 'str'
TypeError
def __lt__(self, other): """Implement the less-than operand.""" if hasattr(other, "alphabet"): if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]): warnings.warn( "Incompatible alphabets {0!r} and {1!r}".format( self.alphabet, other.alphabet ), BiopythonWarning, ) if isinstance(other, MutableSeq): return self.data < other.data if isinstance(other, (str, Seq, UnknownSeq)): return str(self) < str(other) raise TypeError( "'<' not supported between instances of '{}' and '{}'".format( type(self).__name__, type(other).__name__ ) )
def __lt__(self, other): """Implement the less-than operand.""" if hasattr(other, "alphabet"): if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]): warnings.warn( "Incompatible alphabets {0!r} and {1!r}".format( self.alphabet, other.alphabet ), BiopythonWarning, ) if isinstance(other, MutableSeq): return self.data < other.data return str(self) < str(other)
https://github.com/biopython/biopython/issues/1750
from Bio.Seq import Seq 'A' > Seq('A') False Seq('A') > 'A' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '>' not supported between instances of 'Seq' and 'str'
TypeError
def __le__(self, other): """Implement the less-than or equal operand.""" if hasattr(other, "alphabet"): if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]): warnings.warn( "Incompatible alphabets {0!r} and {1!r}".format( self.alphabet, other.alphabet ), BiopythonWarning, ) if isinstance(other, MutableSeq): return self.data <= other.data if isinstance(other, (str, Seq, UnknownSeq)): return str(self) <= str(other) raise TypeError( "'<=' not supported between instances of '{}' and '{}'".format( type(self).__name__, type(other).__name__ ) )
def __le__(self, other): """Implement the less-than or equal operand.""" if hasattr(other, "alphabet"): if not Alphabet._check_type_compatible([self.alphabet, other.alphabet]): warnings.warn( "Incompatible alphabets {0!r} and {1!r}".format( self.alphabet, other.alphabet ), BiopythonWarning, ) if isinstance(other, MutableSeq): return self.data <= other.data return str(self) <= str(other)
https://github.com/biopython/biopython/issues/1750
from Bio.Seq import Seq 'A' > Seq('A') False Seq('A') > 'A' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '>' not supported between instances of 'Seq' and 'str'
TypeError
def admin_upgrade(): """Display any available upgrades and option to upgrade""" if not utils_general.user_has_permission("edit_settings"): return redirect(url_for("routes_general.home")) misc = Misc.query.first() if not internet( host=misc.net_test_ip, port=misc.net_test_port, timeout=misc.net_test_timeout ): return render_template("admin/upgrade.html", is_internet=False) # Read from the upgrade status file created by the upgrade script # to indicate if the upgrade is running. try: with open(UPGRADE_INIT_FILE) as f: upgrade = int(f.read(1)) except IOError: try: with open(UPGRADE_INIT_FILE, "w") as f: f.write("0") finally: upgrade = 0 if upgrade: if upgrade == 2: flash( gettext( "There was an error encountered during the upgrade" " process. Check the upgrade log for details." ), "error", ) return render_template( "admin/upgrade.html", current_release=MYCODO_VERSION, upgrade=upgrade ) form_backup = forms_misc.Backup() form_upgrade = forms_misc.Upgrade() is_internet = True upgrade_available = False # Check for any new Mycodo releases on github mycodo_releases = MycodoRelease() (upgrade_exists, releases, mycodo_releases, current_latest_release, errors) = ( mycodo_releases.github_upgrade_exists() ) if errors: for each_error in errors: flash(each_error, "error") if releases: current_latest_major_version = current_latest_release.split(".")[0] current_major_release = releases[0] current_releases = [] releases_behind = None for index, each_release in enumerate(releases): if parse_version(each_release) >= parse_version(MYCODO_VERSION): current_releases.append(each_release) if parse_version(each_release) == parse_version(MYCODO_VERSION): releases_behind = index if upgrade_exists: upgrade_available = True else: current_releases = [] current_latest_major_version = "0" current_major_release = "0.0.0" releases_behind = 0 # Update database to reflect the current upgrade status mod_misc = Misc.query.first() if mod_misc.mycodo_upgrade_available != upgrade_available: mod_misc.mycodo_upgrade_available = upgrade_available db.session.commit() def not_enough_space_upgrade(): backup_size, free_before, free_after = can_perform_backup() if free_after / 1000000 < 50: flash( "A backup must be performed during an upgrade and there is " "not enough free space to perform a backup. A backup " "requires {size_bu:.1f} MB but there is only {size_free:.1f} " "MB available, which would leave {size_after:.1f} MB after " "the backup. If the free space after a backup is less than 50" " MB, the backup cannot proceed. Free up space by deleting " "current backups.".format( size_bu=backup_size / 1000000, size_free=free_before / 1000000, size_after=free_after / 1000000, ), "error", ) return True else: return False if request.method == "POST": if form_upgrade.upgrade.data and (upgrade_available or FORCE_UPGRADE_MASTER): if not_enough_space_upgrade(): pass elif FORCE_UPGRADE_MASTER: try: os.remove(UPGRADE_TMP_LOG_FILE) except FileNotFoundError: pass cmd = ( "{pth}/mycodo/scripts/mycodo_wrapper upgrade-master" " | ts '[%Y-%m-%d %H:%M:%S]' 2>&1 | tee -a {log} {tmp_log}".format( pth=INSTALL_DIRECTORY, log=UPGRADE_LOG_FILE, tmp_log=UPGRADE_TMP_LOG_FILE, ) ) subprocess.Popen(cmd, shell=True) upgrade = 1 flash( gettext("The upgrade (from master branch) has started"), "success" ) else: try: os.remove(UPGRADE_TMP_LOG_FILE) except FileNotFoundError: pass cmd = ( "{pth}/mycodo/scripts/mycodo_wrapper upgrade-release-major {current_maj_version}" " | ts '[%Y-%m-%d %H:%M:%S]' 2>&1 | tee -a {log} {tmp_log}".format( current_maj_version=MYCODO_VERSION.split(".")[0], pth=INSTALL_DIRECTORY, log=UPGRADE_LOG_FILE, tmp_log=UPGRADE_TMP_LOG_FILE, ) ) subprocess.Popen(cmd, shell=True) upgrade = 1 mod_misc = Misc.query.first() mod_misc.mycodo_upgrade_available = False db.session.commit() flash(gettext("The upgrade has started"), "success") elif form_upgrade.upgrade_next_major_version.data and upgrade_available: if not not_enough_space_upgrade(): try: os.remove(UPGRADE_TMP_LOG_FILE) except FileNotFoundError: pass cmd = ( "{pth}/mycodo/scripts/mycodo_wrapper upgrade-release-wipe {ver}" " | ts '[%Y-%m-%d %H:%M:%S]' 2>&1 | tee -a {log} {tmp_log}".format( pth=INSTALL_DIRECTORY, ver=current_latest_major_version, log=UPGRADE_LOG_FILE, tmp_log=UPGRADE_TMP_LOG_FILE, ) ) subprocess.Popen(cmd, shell=True) upgrade = 1 mod_misc = Misc.query.first() mod_misc.mycodo_upgrade_available = False db.session.commit() flash(gettext("The major version upgrade has started"), "success") else: flash(gettext("You cannot upgrade if an upgrade is not available"), "error") return render_template( "admin/upgrade.html", final_releases=FINAL_RELEASES, force_upgrade_master=FORCE_UPGRADE_MASTER, form_backup=form_backup, form_upgrade=form_upgrade, current_release=MYCODO_VERSION, current_releases=current_releases, current_major_release=current_major_release, current_latest_release=current_latest_release, current_latest_major_version=current_latest_major_version, releases_behind=releases_behind, upgrade_available=upgrade_available, upgrade=upgrade, is_internet=is_internet, )
def admin_upgrade(): """Display any available upgrades and option to upgrade""" if not utils_general.user_has_permission("edit_settings"): return redirect(url_for("routes_general.home")) misc = Misc.query.first() if not internet( host=misc.net_test_ip, port=misc.net_test_port, timeout=misc.net_test_timeout ): flash( gettext( "Upgrade functionality is disabled because an internet " "connection was unable to be detected" ), "error", ) return render_template("admin/upgrade.html", is_internet=False) # Read from the upgrade status file created by the upgrade script # to indicate if the upgrade is running. try: with open(UPGRADE_INIT_FILE) as f: upgrade = int(f.read(1)) except IOError: try: with open(UPGRADE_INIT_FILE, "w") as f: f.write("0") finally: upgrade = 0 if upgrade: if upgrade == 2: flash( gettext( "There was an error encountered during the upgrade" " process. Check the upgrade log for details." ), "error", ) return render_template( "admin/upgrade.html", current_release=MYCODO_VERSION, upgrade=upgrade ) form_backup = forms_misc.Backup() form_upgrade = forms_misc.Upgrade() is_internet = True upgrade_available = False # Check for any new Mycodo releases on github mycodo_releases = MycodoRelease() (upgrade_exists, releases, mycodo_releases, current_latest_release, errors) = ( mycodo_releases.github_upgrade_exists() ) if errors: for each_error in errors: flash(each_error, "error") if releases: current_latest_major_version = current_latest_release.split(".")[0] current_major_release = releases[0] current_releases = [] releases_behind = None for index, each_release in enumerate(releases): if parse_version(each_release) >= parse_version(MYCODO_VERSION): current_releases.append(each_release) if parse_version(each_release) == parse_version(MYCODO_VERSION): releases_behind = index if upgrade_exists: upgrade_available = True else: current_releases = [] current_latest_major_version = "0" current_major_release = "0.0.0" releases_behind = 0 # Update database to reflect the current upgrade status mod_misc = Misc.query.first() if mod_misc.mycodo_upgrade_available != upgrade_available: mod_misc.mycodo_upgrade_available = upgrade_available db.session.commit() def not_enough_space_upgrade(): backup_size, free_before, free_after = can_perform_backup() if free_after / 1000000 < 50: flash( "A backup must be performed during an upgrade and there is " "not enough free space to perform a backup. A backup " "requires {size_bu:.1f} MB but there is only {size_free:.1f} " "MB available, which would leave {size_after:.1f} MB after " "the backup. If the free space after a backup is less than 50" " MB, the backup cannot proceed. Free up space by deleting " "current backups.".format( size_bu=backup_size / 1000000, size_free=free_before / 1000000, size_after=free_after / 1000000, ), "error", ) return True else: return False if request.method == "POST": if form_upgrade.upgrade.data and (upgrade_available or FORCE_UPGRADE_MASTER): if not_enough_space_upgrade(): pass elif FORCE_UPGRADE_MASTER: try: os.remove(UPGRADE_TMP_LOG_FILE) except FileNotFoundError: pass cmd = ( "{pth}/mycodo/scripts/mycodo_wrapper upgrade-master" " | ts '[%Y-%m-%d %H:%M:%S]' 2>&1 | tee -a {log} {tmp_log}".format( pth=INSTALL_DIRECTORY, log=UPGRADE_LOG_FILE, tmp_log=UPGRADE_TMP_LOG_FILE, ) ) subprocess.Popen(cmd, shell=True) upgrade = 1 flash( gettext("The upgrade (from master branch) has started"), "success" ) else: try: os.remove(UPGRADE_TMP_LOG_FILE) except FileNotFoundError: pass cmd = ( "{pth}/mycodo/scripts/mycodo_wrapper upgrade-release-major {current_maj_version}" " | ts '[%Y-%m-%d %H:%M:%S]' 2>&1 | tee -a {log} {tmp_log}".format( current_maj_version=MYCODO_VERSION.split(".")[0], pth=INSTALL_DIRECTORY, log=UPGRADE_LOG_FILE, tmp_log=UPGRADE_TMP_LOG_FILE, ) ) subprocess.Popen(cmd, shell=True) upgrade = 1 mod_misc = Misc.query.first() mod_misc.mycodo_upgrade_available = False db.session.commit() flash(gettext("The upgrade has started"), "success") elif form_upgrade.upgrade_next_major_version.data and upgrade_available: if not not_enough_space_upgrade(): try: os.remove(UPGRADE_TMP_LOG_FILE) except FileNotFoundError: pass cmd = ( "{pth}/mycodo/scripts/mycodo_wrapper upgrade-release-wipe {ver}" " | ts '[%Y-%m-%d %H:%M:%S]' 2>&1 | tee -a {log} {tmp_log}".format( pth=INSTALL_DIRECTORY, ver=current_latest_major_version, log=UPGRADE_LOG_FILE, tmp_log=UPGRADE_TMP_LOG_FILE, ) ) subprocess.Popen(cmd, shell=True) upgrade = 1 mod_misc = Misc.query.first() mod_misc.mycodo_upgrade_available = False db.session.commit() flash(gettext("The major version upgrade has started"), "success") else: flash(gettext("You cannot upgrade if an upgrade is not available"), "error") return render_template( "admin/upgrade.html", final_releases=FINAL_RELEASES, force_upgrade_master=FORCE_UPGRADE_MASTER, form_backup=form_backup, form_upgrade=form_upgrade, current_release=MYCODO_VERSION, current_releases=current_releases, current_major_release=current_major_release, current_latest_release=current_latest_release, current_latest_major_version=current_latest_major_version, releases_behind=releases_behind, upgrade_available=upgrade_available, upgrade=upgrade, is_internet=is_internet, )
https://github.com/kizniche/Mycodo/issues/869
Traceback (most recent call last): File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask_restx/api.py", line 639, in error_router return original_handler(e) File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise raise value File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask_login/utils.py", line 272, in decorated_view return func(*args, **kwargs) File "/home/pi/Mycodo/mycodo/mycodo_flask/routes_admin.py", line 423, in admin_upgrade is_internet=False) File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask/templating.py", line 140, in render_template ctx.app, File "/home/pi/Mycodo/env/lib/python3.7/site-packages/flask/templating.py", line 120, in _render rv = template.render(context) File "/home/pi/Mycodo/env/lib/python3.7/site-packages/jinja2/environment.py", line 1090, in render self.environment.handle_exception() File "/home/pi/Mycodo/env/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception reraise(*rewrite_traceback_stack(source=source)) File "/home/pi/Mycodo/env/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise raise value.with_traceback(tb) File "/home/pi/Mycodo/mycodo/mycodo_flask/templates/admin/upgrade.html", line 2, in top-level template code {% set active_page = "upgrade" %} File "/home/pi/Mycodo/mycodo/mycodo_flask/templates/layout.html", line 325, in top-level template code {%- block body %}{% endblock -%} File "/home/pi/Mycodo/mycodo/mycodo_flask/templates/admin/upgrade.html", line 52, in block "body" {% elif current_latest_major_version != current_release.split('.')[0] and File "/home/pi/Mycodo/env/lib/python3.7/site-packages/jinja2/environment.py", line 471, in getattr return getattr(obj, attribute) jinja2.exceptions.UndefinedError: 'current_release' is undefined
jinja2.exceptions.UndefinedError
def read_last_influxdb(device_id, measure_type, duration_sec=None): """ Query Influxdb for the last entry. example: read_last_influxdb('00000001', 'temperature') :return: list of time and value :rtype: list :param device_id: What device_id tag to query in the Influxdb database (ex. '00000001') :type device_id: str :param measure_type: What measurement to query in the Influxdb database (ex. 'temperature', 'duration') :type measure_type: str :param duration_sec: How many seconds to look for a past measurement :type duration_sec: int """ client = InfluxDBClient( INFLUXDB_HOST, INFLUXDB_PORT, INFLUXDB_USER, INFLUXDB_PASSWORD, INFLUXDB_DATABASE, ) if duration_sec: query = query_string(measure_type, device_id, past_sec=duration_sec) else: query = query_string(measure_type, device_id, value="LAST") try: last_measurement = client.query(query).raw except requests.exceptions.ConnectionError: logger.debug( "Failed to establish a new influxdb connection. Ensure influxdb is running." ) last_measurement = None if last_measurement: try: number = len(last_measurement["series"][0]["values"]) last_time = last_measurement["series"][0]["values"][number - 1][0] last_measurement = last_measurement["series"][0]["values"][number - 1][1] return [last_time, last_measurement] except KeyError: if duration_sec: logger.debug( "No measurement available in the past {sec} seconds.".format( sec=duration_sec ) ) else: logger.debug("No measurement available.") except Exception: logger.exception("Error parsing the last influx measurement")
def read_last_influxdb(device_id, measure_type, duration_sec=None): """ Query Influxdb for the last entry. example: read_last_influxdb('00000001', 'temperature') :return: list of time and value :rtype: list :param device_id: What device_id tag to query in the Influxdb database (ex. '00000001') :type device_id: str :param measure_type: What measurement to query in the Influxdb database (ex. 'temperature', 'duration') :type measure_type: str :param duration_sec: How many seconds to look for a past measurement :type duration_sec: int """ client = InfluxDBClient( INFLUXDB_HOST, INFLUXDB_PORT, INFLUXDB_USER, INFLUXDB_PASSWORD, INFLUXDB_DATABASE, ) if duration_sec: query = query_string(measure_type, device_id, past_sec=duration_sec) else: query = query_string(measure_type, device_id, value="LAST") last_measurement = client.query(query).raw if last_measurement: try: number = len(last_measurement["series"][0]["values"]) last_time = last_measurement["series"][0]["values"][number - 1][0] last_measurement = last_measurement["series"][0]["values"][number - 1][1] return [last_time, last_measurement] except KeyError: if duration_sec: logger.debug( "No measurement available in the past {sec} seconds.".format( sec=duration_sec ) ) else: logger.debug("No measurement available.") except Exception: logger.exception("Error parsing the last influx measurement")
https://github.com/kizniche/Mycodo/issues/405
2018-02-13 04:49:13,135 - mycodo.math_3 - ERROR - Run Error: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?db=mycodo_db&amp;q=SELECT+value+FROM+temperature+WHERE+device_id%3D%2773103a85-ca36-4f55-9443-8b18f13792fa%27+AND+time+%3E+now%28%29+-+60s (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xb4fa2d90>: Failed to establish a new connection: [Errno 111] Connection refused',)) Traceback (most recent call last): File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connection.py", line 141, in _new_conn (self.host, self.port), self.timeout, **extra_kw) File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/util/connection.py", line 83, in create_connection raise err File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/util/connection.py", line 73, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connectionpool.py", line 601, in urlopen chunked=chunked) File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connectionpool.py", line 357, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3.5/http/client.py", line 1107, in request self._send_request(method, url, body, headers) File "/usr/lib/python3.5/http/client.py", line 1152, in _send_request self.endheaders(body) File "/usr/lib/python3.5/http/client.py", line 1103, in endheaders self._send_output(message_body) File "/usr/lib/python3.5/http/client.py", line 934, in _send_output self.send(msg) File "/usr/lib/python3.5/http/client.py", line 877, in send self.connect() File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connection.py", line 166, in connect conn = self._new_conn() File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connection.py", line 150, in _new_conn self, "Failed to establish a new connection: %s" % e) urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0xb4fa2d90>: Failed to establish a new connection: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/mycodo-root/env/lib/python3.5/site-packages/requests/adapters.py", line 440, in send timeout=timeout File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/util/retry.py", line 388, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?db=mycodo_db&amp;q=SELECT+value+FROM+temperature+WHERE+device_id%3D%2773103a85-ca36-4f55-9443-8b18f13792fa%27+AND+time+%3E+now%28%29+-+60s (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xb4fa2d90>: Failed to establish a new connection: [Errno 111] Connection refused',)) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/mycodo-root/mycodo/controller_math.py", line 186, in run success, measure = self.get_measurements_from_str(self.equation_input) File "/var/mycodo-root/mycodo/controller_math.py", line 325, in get_measurements_from_str self.max_measure_age) File "/var/mycodo-root/mycodo/utils/influx.py", line 141, in read_last_influxdb last_measurement = client.query(query).raw File "/var/mycodo-root/env/lib/python3.5/site-packages/influxdb/client.py", line 394, in query expected_response_code=expected_response_code File "/var/mycodo-root/env/lib/python3.5/site-packages/influxdb/client.py", line 252, in request timeout=self._timeout File "/var/mycodo-root/env/lib/python3.5/site-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/var/mycodo-root/env/lib/python3.5/site-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/var/mycodo-root/env/lib/python3.5/site-packages/requests/adapters.py", line 508, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?db=mycodo_db&amp;q=SELECT+value+FROM+temperature+WHERE+device_id%3D%2773103a85-ca36-4f55-9443-8b18f13792fa%27+AND+time+%3E+now%28%29+-+60s (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xb4fa2d90>: Failed to establish a new connection: [Errno 111] Connection refused',))
ConnectionRefusedError
def sensor_add(form_add_sensor): action = "{action} {controller}".format( action=gettext("Add"), controller=gettext("Sensor") ) error = [] if form_add_sensor.validate(): for _ in range(0, form_add_sensor.numberSensors.data): new_sensor = Sensor() new_sensor.device = form_add_sensor.sensor.data new_sensor.name = "{name} Sensor".format(name=form_add_sensor.sensor.data) if GPIO.RPI_INFO["P1_REVISION"] in [2, 3]: new_sensor.i2c_bus = 1 new_sensor.multiplexer_bus = 1 else: new_sensor.i2c_bus = 0 new_sensor.multiplexer_bus = 0 # Linux command as sensor if form_add_sensor.sensor.data == "LinuxCommand": new_sensor.cmd_command = "shuf -i 50-70 -n 1" new_sensor.cmd_measurement = "Condition" new_sensor.cmd_measurement_units = "unit" # Process monitors elif form_add_sensor.sensor.data == "MYCODO_RAM": new_sensor.measurements = "disk_space" new_sensor.location = "Mycodo_daemon" elif form_add_sensor.sensor.data == "RPi": new_sensor.measurements = "temperature" new_sensor.location = "RPi" elif form_add_sensor.sensor.data == "RPiCPULoad": new_sensor.measurements = "cpu_load_1m,cpu_load_5m,cpu_load_15m" new_sensor.location = "RPi" elif form_add_sensor.sensor.data == "RPiFreeSpace": new_sensor.measurements = "disk_space" new_sensor.location = "/" elif form_add_sensor.sensor.data == "EDGE": new_sensor.measurements = "edge" # Signal measuremnt (PWM and RPM) elif form_add_sensor.sensor.data == "SIGNAL_PWM": new_sensor.measurements = "frequency,pulse_width,duty_cycle" elif form_add_sensor.sensor.data == "SIGNAL_RPM": new_sensor.measurements = "rpm" # Environmental Sensors # Temperature elif form_add_sensor.sensor.data in [ "ATLAS_PT1000_I2C", "ATLAS_PT1000_UART", "DS18B20", "TMP006", ]: new_sensor.measurements = "temperature" if form_add_sensor.sensor.data == "ATLAS_PT1000_I2C": new_sensor.interface = "I2C" new_sensor.location = "0x66" elif form_add_sensor.sensor.data == "ATLAS_PT1000_UART": new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" elif form_add_sensor.sensor.data == "TMP006": new_sensor.measurements = "temperature_object,temperature_die" new_sensor.location = "0x40" # Temperature/Humidity elif form_add_sensor.sensor.data in [ "AM2315", "DHT11", "DHT22", "HTU21D", "SHT1x_7x", "SHT2x", ]: new_sensor.measurements = "temperature,humidity,dewpoint" if form_add_sensor.sensor.data == "AM2315": new_sensor.location = "0x5c" elif form_add_sensor.sensor.data == "HTU21D": new_sensor.location = "0x40" elif form_add_sensor.sensor.data == "SHT2x": new_sensor.location = "0x40" # Chirp moisture sensor elif form_add_sensor.sensor.data == "CHIRP": new_sensor.measurements = "lux,moisture,temperature" new_sensor.location = "0x20" # CO2 elif form_add_sensor.sensor.data == "MH_Z16_I2C": new_sensor.measurements = "co2" new_sensor.location = "0x63" new_sensor.interface = "I2C" elif form_add_sensor.sensor.data in [ "K30_UART", "MH_Z16_UART", "MH_Z19_UART", ]: new_sensor.measurements = "co2" new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" # pH elif form_add_sensor.sensor.data == "ATLAS_PH_I2C": new_sensor.measurements = "ph" new_sensor.location = "0x63" new_sensor.interface = "I2C" elif form_add_sensor.sensor.data == "ATLAS_PH_UART": new_sensor.measurements = "ph" new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" # Pressure elif form_add_sensor.sensor.data in ["BME280", "BMP180", "BMP280"]: if form_add_sensor.sensor.data == "BME280": new_sensor.measurements = ( "temperature,humidity,dewpoint,pressure,altitude" ) new_sensor.location = "0x76" elif form_add_sensor.sensor.data in ["BMP180", "BMP280"]: new_sensor.measurements = "temperature,pressure,altitude" new_sensor.location = "0x77" # Light elif form_add_sensor.sensor.data in ["BH1750", "TSL2561", "TSL2591"]: new_sensor.measurements = "lux" if form_add_sensor.sensor.data == "BH1750": new_sensor.location = "0x23" new_sensor.resolution = 0 # 0=Low, 1=High, 2=High2 new_sensor.sensitivity = 69 elif form_add_sensor.sensor.data == "TSL2561": new_sensor.location = "0x39" elif form_add_sensor.sensor.data == "TSL2591": new_sensor.location = "0x29" # Analog to Digital Converters elif form_add_sensor.sensor.data in ["ADS1x15", "MCP342x"]: new_sensor.measurements = "voltage" if form_add_sensor.sensor.data == "ADS1x15": new_sensor.location = "0x48" new_sensor.adc_volts_min = -4.096 new_sensor.adc_volts_max = 4.096 elif form_add_sensor.sensor.data == "MCP342x": new_sensor.location = "0x68" new_sensor.adc_volts_min = -2.048 new_sensor.adc_volts_max = 2.048 try: new_sensor.save() display_order = csv_to_list_of_int(DisplayOrder.query.first().sensor) DisplayOrder.query.first().sensor = add_display_order( display_order, new_sensor.id ) db.session.commit() flash( gettext( "%(type)s Sensor with ID %(id)s (%(uuid)s) successfully added", type=form_add_sensor.sensor.data, id=new_sensor.id, uuid=new_sensor.unique_id, ), "success", ) except sqlalchemy.exc.OperationalError as except_msg: error.append(except_msg) except sqlalchemy.exc.IntegrityError as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for("page_routes.page_input")) else: flash_form_errors(form_add_sensor)
def sensor_add(form_add_sensor): action = "{action} {controller}".format( action=gettext("Add"), controller=gettext("Sensor") ) error = [] if form_add_sensor.validate(): for _ in range(0, form_add_sensor.numberSensors.data): new_sensor = Sensor() new_sensor.device = form_add_sensor.sensor.data new_sensor.name = "{name} Sensor".format(name=form_add_sensor.sensor.data) if GPIO.RPI_INFO["P1_REVISION"] in [2, 3]: new_sensor.i2c_bus = 1 new_sensor.multiplexer_bus = 1 else: new_sensor.i2c_bus = 0 new_sensor.multiplexer_bus = 0 # Linux command as sensor if form_add_sensor.sensor.data == "LinuxCommand": new_sensor.cmd_command = "shuf -i 50-70 -n 1" new_sensor.cmd_measurement = "Condition" new_sensor.cmd_measurement_units = "unit" # Process monitors elif form_add_sensor.sensor.data == "MYCODO_RAM": new_sensor.measurements = "disk_space" new_sensor.location = "Mycodo_daemon" elif form_add_sensor.sensor.data == "RPi": new_sensor.measurements = "temperature" new_sensor.location = "RPi" elif form_add_sensor.sensor.data == "RPiCPULoad": new_sensor.measurements = "cpu_load_1m,cpu_load_5m,cpu_load_15m" new_sensor.location = "RPi" elif form_add_sensor.sensor.data == "RPiFreeSpace": new_sensor.measurements = "disk_space" new_sensor.location = "/" elif form_add_sensor.sensor.data == "EDGE": new_sensor.measurements = "edge" # Environmental Sensors # Temperature elif form_add_sensor.sensor.data in [ "ATLAS_PT1000_I2C", "ATLAS_PT1000_UART", "DS18B20", "TMP006", ]: new_sensor.measurements = "temperature" if form_add_sensor.sensor.data == "ATLAS_PT1000_I2C": new_sensor.interface = "I2C" new_sensor.location = "0x66" elif form_add_sensor.sensor.data == "ATLAS_PT1000_UART": new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" elif form_add_sensor.sensor.data == "TMP006": new_sensor.measurements = "temperature_object,temperature_die" new_sensor.location = "0x40" # Temperature/Humidity elif form_add_sensor.sensor.data in [ "AM2315", "DHT11", "DHT22", "HTU21D", "SHT1x_7x", "SHT2x", ]: new_sensor.measurements = "temperature,humidity,dewpoint" if form_add_sensor.sensor.data == "AM2315": new_sensor.location = "0x5c" elif form_add_sensor.sensor.data == "HTU21D": new_sensor.location = "0x40" elif form_add_sensor.sensor.data == "SHT2x": new_sensor.location = "0x40" # Chirp moisture sensor elif form_add_sensor.sensor.data == "CHIRP": new_sensor.measurements = "lux,moisture,temperature" new_sensor.location = "0x20" # CO2 elif form_add_sensor.sensor.data == "MH_Z16_I2C": new_sensor.measurements = "co2" new_sensor.location = "0x63" new_sensor.interface = "I2C" elif form_add_sensor.sensor.data in [ "K30_UART", "MH_Z16_UART", "MH_Z19_UART", ]: new_sensor.measurements = "co2" new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" # pH elif form_add_sensor.sensor.data == "ATLAS_PH_I2C": new_sensor.measurements = "ph" new_sensor.location = "0x63" new_sensor.interface = "I2C" elif form_add_sensor.sensor.data == "ATLAS_PH_UART": new_sensor.measurements = "ph" new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" # Pressure elif form_add_sensor.sensor.data in ["BME280", "BMP180", "BMP280"]: if form_add_sensor.sensor.data == "BME280": new_sensor.measurements = ( "temperature,humidity,dewpoint,pressure,altitude" ) new_sensor.location = "0x76" elif form_add_sensor.sensor.data in ["BMP180", "BMP280"]: new_sensor.measurements = "temperature,pressure,altitude" new_sensor.location = "0x77" # Light elif form_add_sensor.sensor.data in ["BH1750", "TSL2561", "TSL2591"]: new_sensor.measurements = "lux" if form_add_sensor.sensor.data == "BH1750": new_sensor.location = "0x23" new_sensor.resolution = 0 # 0=Low, 1=High, 2=High2 new_sensor.sensitivity = 69 elif form_add_sensor.sensor.data == "TSL2561": new_sensor.location = "0x39" elif form_add_sensor.sensor.data == "TSL2591": new_sensor.location = "0x29" # Analog to Digital Converters elif form_add_sensor.sensor.data in ["ADS1x15", "MCP342x"]: new_sensor.measurements = "voltage" if form_add_sensor.sensor.data == "ADS1x15": new_sensor.location = "0x48" new_sensor.adc_volts_min = -4.096 new_sensor.adc_volts_max = 4.096 elif form_add_sensor.sensor.data == "MCP342x": new_sensor.location = "0x68" new_sensor.adc_volts_min = -2.048 new_sensor.adc_volts_max = 2.048 try: new_sensor.save() display_order = csv_to_list_of_int(DisplayOrder.query.first().sensor) DisplayOrder.query.first().sensor = add_display_order( display_order, new_sensor.id ) db.session.commit() flash( gettext( "%(type)s Sensor with ID %(id)s (%(uuid)s) successfully added", type=form_add_sensor.sensor.data, id=new_sensor.id, uuid=new_sensor.unique_id, ), "success", ) except sqlalchemy.exc.OperationalError as except_msg: error.append(except_msg) except sqlalchemy.exc.IntegrityError as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for("page_routes.page_input")) else: flash_form_errors(form_add_sensor)
https://github.com/kizniche/Mycodo/issues/304
Error 500: Internal Server Error Something bad happened but it's probably not your fault. Letting the developers know about these issues is crucial to supporting Mycodo. Please submit a new issue on GitHub with the following error traceback (copy the entire traceback): Error (Full Traceback): Traceback (most recent call last): File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask_login/utils.py", line 228, in decorated_view return func(*args, **kwargs) File "/var/www/mycodo/mycodo/mycodo_flask/page_routes.py", line 612, in page_live sensorDisplayOrderSorted=sensor_order_sorted) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/templating.py", line 134, in render_template context, ctx.app) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/templating.py", line 116, in _render rv = template.render(context) File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 1008, in render return self.environment.handle_exception(exc_info, True) File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb) File "/var/www/mycodo/mycodo/mycodo_flask/templates/pages/live.html", line 3, in top-level template code {% set help_page = ["live-measurements", _('Live Leasurements')] %} File "/var/www/mycodo/mycodo/mycodo_flask/templates/layout.html", line 187, in top-level template code {%- block body %}{% endblock -%} File "/var/www/mycodo/mycodo/mycodo_flask/templates/pages/live.html", line 116, in block "body" {% if measurement_units[each_measure]['meas'] == 'temperature' %} File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 411, in getitem return obj[argument] UndefinedError: 'dict object' has no attribute u''
UndefinedError
def get_measurement(self): """Gets the pwm""" try: pi = pigpio.pi() read_pwm = ReadPWM(pi, self.pin, self.weighting) except Exception: return try: frequency = read_pwm.frequency() pulse_width = read_pwm.pulse_width() duty_cycle = read_pwm.duty_cycle() return frequency, int(pulse_width + 0.5), duty_cycle finally: read_pwm.cancel() pi.stop()
def get_measurement(self): """Gets the pwm""" pi = pigpio.pi() try: read_pwm = ReadPWM(pi, self.pin, self.weighting) frequency = read_pwm.frequency() pulse_width = read_pwm.pulse_width() duty_cycle = read_pwm.duty_cycle() return frequency, int(pulse_width + 0.5), duty_cycle finally: p.cancel() pi.stop()
https://github.com/kizniche/Mycodo/issues/304
Error 500: Internal Server Error Something bad happened but it's probably not your fault. Letting the developers know about these issues is crucial to supporting Mycodo. Please submit a new issue on GitHub with the following error traceback (copy the entire traceback): Error (Full Traceback): Traceback (most recent call last): File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask_login/utils.py", line 228, in decorated_view return func(*args, **kwargs) File "/var/www/mycodo/mycodo/mycodo_flask/page_routes.py", line 612, in page_live sensorDisplayOrderSorted=sensor_order_sorted) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/templating.py", line 134, in render_template context, ctx.app) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/templating.py", line 116, in _render rv = template.render(context) File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 1008, in render return self.environment.handle_exception(exc_info, True) File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb) File "/var/www/mycodo/mycodo/mycodo_flask/templates/pages/live.html", line 3, in top-level template code {% set help_page = ["live-measurements", _('Live Leasurements')] %} File "/var/www/mycodo/mycodo/mycodo_flask/templates/layout.html", line 187, in top-level template code {%- block body %}{% endblock -%} File "/var/www/mycodo/mycodo/mycodo_flask/templates/pages/live.html", line 116, in block "body" {% if measurement_units[each_measure]['meas'] == 'temperature' %} File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 411, in getitem return obj[argument] UndefinedError: 'dict object' has no attribute u''
UndefinedError
def get_measurement(self): """Gets the rpm""" try: pi = pigpio.pi() read_rpm = ReadRPM(pi, self.pin, self.weighting, self.rpm_pulses_per_rev) except Exception: return 0 try: rpm = read_rpm.RPM() if rpm: return int(rpm + 0.5) except Exception: logger.exception(1) finally: read_rpm.cancel() pi.stop() return 0
def get_measurement(self): """Gets the rpm""" pi = pigpio.pi() try: read_rpm = ReadRPM(pi, self.pin, self.weighting, self.rpm_pulses_per_rev) rpm = read_rpm.RPM() if rpm: return int(rpm + 0.5) finally: p.cancel() pi.stop() return None
https://github.com/kizniche/Mycodo/issues/304
Error 500: Internal Server Error Something bad happened but it's probably not your fault. Letting the developers know about these issues is crucial to supporting Mycodo. Please submit a new issue on GitHub with the following error traceback (copy the entire traceback): Error (Full Traceback): Traceback (most recent call last): File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask_login/utils.py", line 228, in decorated_view return func(*args, **kwargs) File "/var/www/mycodo/mycodo/mycodo_flask/page_routes.py", line 612, in page_live sensorDisplayOrderSorted=sensor_order_sorted) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/templating.py", line 134, in render_template context, ctx.app) File "/var/www/mycodo/env/lib/python2.7/site-packages/flask/templating.py", line 116, in _render rv = template.render(context) File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 1008, in render return self.environment.handle_exception(exc_info, True) File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb) File "/var/www/mycodo/mycodo/mycodo_flask/templates/pages/live.html", line 3, in top-level template code {% set help_page = ["live-measurements", _('Live Leasurements')] %} File "/var/www/mycodo/mycodo/mycodo_flask/templates/layout.html", line 187, in top-level template code {%- block body %}{% endblock -%} File "/var/www/mycodo/mycodo/mycodo_flask/templates/pages/live.html", line 116, in block "body" {% if measurement_units[each_measure]['meas'] == 'temperature' %} File "/var/www/mycodo/env/lib/python2.7/site-packages/jinja2/environment.py", line 411, in getitem return obj[argument] UndefinedError: 'dict object' has no attribute u''
UndefinedError
def upgrade(): with op.batch_alter_table("sensor") as batch_op: batch_op.add_column(sa.Column("cmd_command", sa.TEXT)) batch_op.add_column(sa.Column("cmd_measurement", sa.TEXT)) batch_op.add_column(sa.Column("cmd_measurement_units", sa.TEXT)) with op.batch_alter_table("pid") as batch_op: batch_op.drop_column("sensor_id") op.execute( """ UPDATE pid SET measurement='' """ ) op.execute( """ UPDATE pid SET is_activated=0 """ )
def upgrade(): with op.batch_alter_table("sensor") as batch_op: batch_op.add_column(sa.Column("cmd_command", sa.TEXT)) batch_op.add_column(sa.Column("cmd_measurement", sa.TEXT)) batch_op.add_column(sa.Column("cmd_measurement_units", sa.TEXT))
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def downgrade(): with op.batch_alter_table("sensor") as batch_op: batch_op.drop_column("cmd_command") batch_op.drop_column("cmd_measurement") batch_op.drop_column("cmd_measurement_units") with op.batch_alter_table("pid") as batch_op: batch_op.add_column( sa.Column("sensor_id", sa.Integer, sa.ForeignKey("sensor.id")) )
def downgrade(): with op.batch_alter_table("sensor") as batch_op: batch_op.drop_column("cmd_command") batch_op.drop_column("cmd_measurement") batch_op.drop_column("cmd_measurement_units")
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def __init__(self, ready, lcd_id): threading.Thread.__init__(self) self.logger = logging.getLogger("mycodo.lcd_{id}".format(id=lcd_id)) self.running = False self.thread_startup_timer = timeit.default_timer() self.thread_shutdown_timer = 0 self.ready = ready self.flash_lcd_on = False self.lcd_is_on = False self.lcd_id = lcd_id try: lcd = db_retrieve_table_daemon(LCD, device_id=self.lcd_id) self.lcd_name = lcd.name self.lcd_location = lcd.location self.lcd_period = lcd.period self.lcd_x_characters = lcd.x_characters self.lcd_y_lines = lcd.y_lines self.timer = time.time() + self.lcd_period self.backlight_timer = time.time() if lcd.multiplexer_address: self.multiplexer_address_string = lcd.multiplexer_address self.multiplexer_address = int(str(lcd.multiplexer_address), 16) self.multiplexer_channel = lcd.multiplexer_channel self.multiplexer = TCA9548A(self.multiplexer_address) else: self.multiplexer = None self.lcd_line = {} for i in range(1, self.lcd_y_lines + 1): self.lcd_line[i] = {} self.list_pids = ["setpoint", "pid_time"] self.list_relays = ["duration_sec", "relay_time", "relay_state"] self.list_sensors = MEASUREMENT_UNITS self.list_sensors.update({"sensor_time": {"unit": None, "name": "Time"}}) # Add custom measurement and units to list (From linux command sensor) sensor = db_retrieve_table_daemon(Sensor) self.list_sensors = add_custom_measurements( sensor, self.list_sensors, MEASUREMENT_UNITS ) if self.lcd_y_lines in [2, 4]: self.setup_lcd_line(1, lcd.line_1_sensor_id, lcd.line_1_measurement) self.setup_lcd_line(2, lcd.line_2_sensor_id, lcd.line_2_measurement) if self.lcd_y_lines == 4: self.setup_lcd_line(3, lcd.line_3_sensor_id, lcd.line_3_measurement) self.setup_lcd_line(4, lcd.line_4_sensor_id, lcd.line_4_measurement) self.lcd_string_line = {} for i in range(1, self.lcd_y_lines + 1): self.lcd_string_line[i] = "" self.LCD_WIDTH = self.lcd_x_characters # Max characters per line self.LCD_LINE = {1: 0x80, 2: 0xC0, 3: 0x94, 4: 0xD4} self.LCD_CHR = 1 # Mode - Sending data self.LCD_CMD = 0 # Mode - SenLCDding command self.LCD_BACKLIGHT = 0x08 # On self.LCD_BACKLIGHT_OFF = 0x00 # Off self.ENABLE = 0b00000100 # Enable bit # Timing constants self.E_PULSE = 0.0005 self.E_DELAY = 0.0005 # Setup I2C bus try: if GPIO.RPI_REVISION == 2 or GPIO.RPI_REVISION == 3: i2c_bus_number = 1 else: i2c_bus_number = 0 self.bus = smbus.SMBus(i2c_bus_number) except Exception as except_msg: self.logger.exception( "Could not initialize I2C bus: {err}".format(err=except_msg) ) self.I2C_ADDR = int(self.lcd_location, 16) self.lcd_init() self.lcd_string_write("Mycodo {}".format(MYCODO_VERSION), self.LCD_LINE[1]) self.lcd_string_write("Start {}".format(self.lcd_name), self.LCD_LINE[2]) except Exception as except_msg: self.logger.exception("Error: {err}".format(err=except_msg))
def __init__(self, ready, lcd_id): threading.Thread.__init__(self) self.logger = logging.getLogger("mycodo.lcd_{id}".format(id=lcd_id)) self.running = False self.thread_startup_timer = timeit.default_timer() self.thread_shutdown_timer = 0 self.ready = ready self.flash_lcd_on = False self.lcd_is_on = False self.lcd_id = lcd_id try: lcd = db_retrieve_table_daemon(LCD, device_id=self.lcd_id) self.lcd_name = lcd.name self.lcd_location = lcd.location self.lcd_period = lcd.period self.lcd_x_characters = lcd.x_characters self.lcd_y_lines = lcd.y_lines self.timer = time.time() + self.lcd_period self.backlight_timer = time.time() if lcd.multiplexer_address: self.multiplexer_address_string = lcd.multiplexer_address self.multiplexer_address = int(str(lcd.multiplexer_address), 16) self.multiplexer_channel = lcd.multiplexer_channel self.multiplexer = TCA9548A(self.multiplexer_address) else: self.multiplexer = None self.lcd_line = {} for i in range(1, 5): self.lcd_line[i] = {} self.list_sensors = MEASUREMENT_UNITS self.list_sensors.update({"sensor_time": {"unit": None, "name": "Time"}}) self.list_pids = ["setpoint", "pid_time"] self.list_relays = ["duration_sec", "relay_time", "relay_state"] if self.lcd_y_lines in [2, 4]: self.setup_lcd_line(1, lcd.line_1_sensor_id, lcd.line_1_measurement) self.setup_lcd_line(2, lcd.line_2_sensor_id, lcd.line_2_measurement) if self.lcd_y_lines == 4: self.setup_lcd_line(3, lcd.line_3_sensor_id, lcd.line_3_measurement) self.setup_lcd_line(4, lcd.line_4_sensor_id, lcd.line_4_measurement) self.lcd_string_line = {} for i in range(1, self.lcd_y_lines + 1): self.lcd_string_line[i] = "" self.LCD_WIDTH = self.lcd_x_characters # Max characters per line self.LCD_LINE = {1: 0x80, 2: 0xC0, 3: 0x94, 4: 0xD4} self.LCD_CHR = 1 # Mode - Sending data self.LCD_CMD = 0 # Mode - SenLCDding command self.LCD_BACKLIGHT = 0x08 # On self.LCD_BACKLIGHT_OFF = 0x00 # Off self.ENABLE = 0b00000100 # Enable bit # Timing constants self.E_PULSE = 0.0005 self.E_DELAY = 0.0005 # Setup I2C bus try: if GPIO.RPI_REVISION == 2 or GPIO.RPI_REVISION == 3: i2c_bus_number = 1 else: i2c_bus_number = 0 self.bus = smbus.SMBus(i2c_bus_number) except Exception as except_msg: self.logger.exception( "Could not initialize I2C bus: {err}".format(err=except_msg) ) self.I2C_ADDR = int(self.lcd_location, 16) self.lcd_init() self.lcd_string_write("Mycodo {}".format(MYCODO_VERSION), self.LCD_LINE[1]) self.lcd_string_write("Start {}".format(self.lcd_name), self.LCD_LINE[2]) except Exception as except_msg: self.logger.exception("Error: {err}".format(err=except_msg))
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def create_lcd_line(self, last_measurement_success, i): try: if last_measurement_success: # Determine if the LCD output will have a value unit measurement = "" if self.lcd_line[i]["measurement"] == "setpoint": pid = db_retrieve_table_daemon(PID, unique_id=self.lcd_line[i]["id"]) measurement = pid.measurement.split(",")[1] self.lcd_line[i]["measurement_value"] = "{:.2f}".format( self.lcd_line[i]["measurement_value"] ) elif self.lcd_line[i]["measurement"] == "duration_sec": measurement = "duration_sec" self.lcd_line[i]["measurement_value"] = "{:.2f}".format( self.lcd_line[i]["measurement_value"] ) elif self.lcd_line[i]["measurement"] in self.list_sensors: measurement = self.lcd_line[i]["measurement"] # Produce the line that will be displayed on the LCD number_characters = self.lcd_x_characters if self.lcd_line[i]["measurement"] == "time": # Convert UTC timestamp to local timezone utc_dt = datetime.datetime.strptime( self.lcd_line[i]["time"].split(".")[0], "%Y-%m-%dT%H:%M:%S" ) utc_timestamp = calendar.timegm(utc_dt.timetuple()) self.lcd_string_line[i] = str( datetime.datetime.fromtimestamp(utc_timestamp) ) elif measurement: value_length = len(str(self.lcd_line[i]["measurement_value"])) unit_length = len(self.list_sensors[measurement]["unit"]) name_length = number_characters - value_length - unit_length - 2 name_cropped = self.lcd_line[i]["name"].ljust(name_length)[:name_length] self.lcd_string_line[i] = "{name} {value} {unit}".format( name=name_cropped, value=self.lcd_line[i]["measurement_value"], unit=self.list_sensors[measurement]["unit"], ) else: value_length = len(str(self.lcd_line[i]["measurement_value"])) name_length = number_characters - value_length - 1 name_cropped = self.lcd_line[i]["name"][:name_length] self.lcd_string_line[i] = "{name} {value}".format( name=name_cropped, value=self.lcd_line[i]["measurement_value"] ) else: self.lcd_string_line[i] = "ERROR: NO DATA" except Exception as except_msg: self.logger.exception("Error: {err}".format(err=except_msg))
def create_lcd_line(self, last_measurement_success, i): try: if last_measurement_success: # Determine if the LCD output will have a value unit measurement = "" if self.lcd_line[i]["measurement"] == "setpoint": pid = db_retrieve_table_daemon(PID, unique_id=self.lcd_line[i]["id"]) measurement = pid.measurement self.lcd_line[i]["measurement_value"] = "{:.2f}".format( self.lcd_line[i]["measurement_value"] ) elif self.lcd_line[i]["measurement"] == "duration_sec": measurement = "duration_sec" self.lcd_line[i]["measurement_value"] = "{:.2f}".format( self.lcd_line[i]["measurement_value"] ) elif self.lcd_line[i]["measurement"] in MEASUREMENT_UNITS: measurement = self.lcd_line[i]["measurement"] # Produce the line that will be displayed on the LCD number_characters = self.lcd_x_characters if self.lcd_line[i]["measurement"] == "time": # Convert UTC timestamp to local timezone utc_dt = datetime.datetime.strptime( self.lcd_line[i]["time"].split(".")[0], "%Y-%m-%dT%H:%M:%S" ) utc_timestamp = calendar.timegm(utc_dt.timetuple()) self.lcd_string_line[i] = str( datetime.datetime.fromtimestamp(utc_timestamp) ) elif measurement: value_length = len(str(self.lcd_line[i]["measurement_value"])) unit_length = len(MEASUREMENT_UNITS[measurement]["unit"]) name_length = number_characters - value_length - unit_length - 2 name_cropped = self.lcd_line[i]["name"].ljust(name_length)[:name_length] self.lcd_string_line[i] = "{name} {value} {unit}".format( name=name_cropped, value=self.lcd_line[i]["measurement_value"], unit=MEASUREMENT_UNITS[measurement]["unit"], ) else: value_length = len(str(self.lcd_line[i]["measurement_value"])) name_length = number_characters - value_length - 1 name_cropped = self.lcd_line[i]["name"][:name_length] self.lcd_string_line[i] = "{name} {value}".format( name=name_cropped, value=self.lcd_line[i]["measurement_value"] ) else: self.lcd_string_line[i] = "ERROR: NO DATA" except Exception as except_msg: self.logger.exception("Error: {err}".format(err=except_msg))
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def initialize_values(self): """Set PID parameters""" pid = db_retrieve_table_daemon(PID, device_id=self.pid_id) self.is_activated = pid.is_activated self.is_held = pid.is_held self.is_paused = pid.is_paused self.pid_type = pid.pid_type self.method_id = pid.method_id self.direction = pid.direction self.raise_relay_id = pid.raise_relay_id self.raise_min_duration = pid.raise_min_duration self.raise_max_duration = pid.raise_max_duration self.raise_min_off_duration = pid.raise_min_off_duration self.lower_relay_id = pid.lower_relay_id self.lower_min_duration = pid.lower_min_duration self.lower_max_duration = pid.lower_max_duration self.lower_min_off_duration = pid.lower_min_off_duration self.Kp = pid.p self.Ki = pid.i self.Kd = pid.d self.integrator_min = pid.integrator_min self.integrator_max = pid.integrator_max self.period = pid.period self.max_measure_age = pid.max_measure_age self.default_set_point = pid.setpoint self.set_point = pid.setpoint sensor_unique_id = pid.measurement.split(",")[0] self.measurement = pid.measurement.split(",")[1] sensor = db_retrieve_table_daemon(Sensor, unique_id=sensor_unique_id) self.sensor_unique_id = sensor.unique_id self.sensor_duration = sensor.period return "success"
def initialize_values(self): """Set PID parameters""" pid = db_retrieve_table_daemon(PID, device_id=self.pid_id) self.is_activated = pid.is_activated self.is_held = pid.is_held self.is_paused = pid.is_paused self.pid_type = pid.pid_type self.measurement = pid.measurement self.method_id = pid.method_id self.direction = pid.direction self.raise_relay_id = pid.raise_relay_id self.raise_min_duration = pid.raise_min_duration self.raise_max_duration = pid.raise_max_duration self.raise_min_off_duration = pid.raise_min_off_duration self.lower_relay_id = pid.lower_relay_id self.lower_min_duration = pid.lower_min_duration self.lower_max_duration = pid.lower_max_duration self.lower_min_off_duration = pid.lower_min_off_duration self.Kp = pid.p self.Ki = pid.i self.Kd = pid.d self.integrator_min = pid.integrator_min self.integrator_max = pid.integrator_max self.period = pid.period self.max_measure_age = pid.max_measure_age self.default_set_point = pid.setpoint self.set_point = pid.setpoint sensor = db_retrieve_table_daemon(Sensor, device_id=pid.sensor_id) self.sensor_unique_id = sensor.unique_id self.sensor_duration = sensor.period return "success"
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def pid_mod(form_mod_pid_base, form_mod_pid_pwm, form_mod_pid_relay): action = "{action} {controller}".format( action=gettext("Modify"), controller=gettext("PID") ) error = [] if not form_mod_pid_base.validate(): flash_form_errors(form_mod_pid_base) try: sensor_unique_id = form_mod_pid_base.measurement.data.split(",")[0] sensor = Sensor.query.filter(Sensor.unique_id == sensor_unique_id).first() if not sensor: error.append(gettext("A valid sensor is required")) if not error: mod_pid = PID.query.filter(PID.id == form_mod_pid_base.pid_id.data).first() mod_pid.name = form_mod_pid_base.name.data mod_pid.measurement = form_mod_pid_base.measurement.data mod_pid.direction = form_mod_pid_base.direction.data mod_pid.period = form_mod_pid_base.period.data mod_pid.max_measure_age = form_mod_pid_base.max_measure_age.data mod_pid.setpoint = form_mod_pid_base.setpoint.data mod_pid.p = form_mod_pid_base.k_p.data mod_pid.i = form_mod_pid_base.k_i.data mod_pid.d = form_mod_pid_base.k_d.data mod_pid.integrator_min = form_mod_pid_base.integrator_max.data mod_pid.integrator_max = form_mod_pid_base.integrator_min.data if form_mod_pid_base.method_id.data: mod_pid.method_id = form_mod_pid_base.method_id.data else: mod_pid.method_id = None if mod_pid.pid_type == "relay": if not form_mod_pid_relay.validate(): flash_form_errors(form_mod_pid_relay) else: if form_mod_pid_relay.raise_relay_id.data: mod_pid.raise_relay_id = form_mod_pid_relay.raise_relay_id.data else: mod_pid.raise_relay_id = None mod_pid.raise_min_duration = ( form_mod_pid_relay.raise_min_duration.data ) mod_pid.raise_max_duration = ( form_mod_pid_relay.raise_max_duration.data ) mod_pid.raise_min_off_duration = ( form_mod_pid_relay.raise_min_off_duration.data ) if form_mod_pid_relay.lower_relay_id.data: mod_pid.lower_relay_id = form_mod_pid_relay.lower_relay_id.data else: mod_pid.lower_relay_id = None mod_pid.lower_min_duration = ( form_mod_pid_relay.lower_min_duration.data ) mod_pid.lower_max_duration = ( form_mod_pid_relay.lower_max_duration.data ) mod_pid.lower_min_off_duration = ( form_mod_pid_relay.lower_min_off_duration.data ) elif mod_pid.pid_type == "pwm": if not form_mod_pid_pwm.validate(): flash_form_errors(form_mod_pid_pwm) else: if form_mod_pid_relay.raise_relay_id.data: mod_pid.raise_relay_id = form_mod_pid_pwm.raise_relay_id.data else: mod_pid.raise_relay_id = None if form_mod_pid_relay.lower_relay_id.data: mod_pid.lower_relay_id = form_mod_pid_pwm.lower_relay_id.data else: mod_pid.lower_relay_id = None mod_pid.raise_min_duration = ( form_mod_pid_pwm.raise_min_duty_cycle.data ) mod_pid.raise_max_duration = ( form_mod_pid_pwm.raise_max_duty_cycle.data ) mod_pid.lower_min_duration = ( form_mod_pid_pwm.lower_min_duty_cycle.data ) mod_pid.lower_max_duration = ( form_mod_pid_pwm.lower_max_duty_cycle.data ) db.session.commit() # If the controller is active or paused, refresh variables in thread if mod_pid.is_activated: control = DaemonControl() return_value = control.pid_mod(form_mod_pid_base.pid_id.data) flash( gettext( "PID Controller settings refresh response: %(resp)s", resp=return_value, ), "success", ) except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for("page_routes.page_pid"))
def pid_mod(form_mod_pid_base, form_mod_pid_pwm, form_mod_pid_relay): action = "{action} {controller}".format( action=gettext("Modify"), controller=gettext("PID") ) error = [] if not form_mod_pid_base.validate(): flash_form_errors(form_mod_pid_base) try: sensor = Sensor.query.filter( Sensor.id == form_mod_pid_base.sensor_id.data ).first() if not sensor: error.append(gettext("A valid sensor ID is required")) elif sensor.device != "LinuxCommand" and sensor.device not in MEASUREMENTS: error.append(gettext("Invalid sensor")) elif ( sensor.device != "LinuxCommand" and form_mod_pid_base.measurement.data not in MEASUREMENTS[sensor.device] ): error.append( gettext( "Select a Measure Type that is compatible with the chosen sensor" ) ) if not error: mod_pid = PID.query.filter(PID.id == form_mod_pid_base.pid_id.data).first() mod_pid.name = form_mod_pid_base.name.data if form_mod_pid_base.sensor_id.data: mod_pid.sensor_id = form_mod_pid_base.sensor_id.data else: mod_pid.sensor_id = None mod_pid.measurement = form_mod_pid_base.measurement.data mod_pid.direction = form_mod_pid_base.direction.data mod_pid.period = form_mod_pid_base.period.data mod_pid.max_measure_age = form_mod_pid_base.max_measure_age.data mod_pid.setpoint = form_mod_pid_base.setpoint.data mod_pid.p = form_mod_pid_base.k_p.data mod_pid.i = form_mod_pid_base.k_i.data mod_pid.d = form_mod_pid_base.k_d.data mod_pid.integrator_min = form_mod_pid_base.integrator_max.data mod_pid.integrator_max = form_mod_pid_base.integrator_min.data if form_mod_pid_base.method_id.data: mod_pid.method_id = form_mod_pid_base.method_id.data else: mod_pid.method_id = None if mod_pid.pid_type == "relay": if not form_mod_pid_relay.validate(): flash_form_errors(form_mod_pid_relay) else: if form_mod_pid_relay.raise_relay_id.data: mod_pid.raise_relay_id = form_mod_pid_relay.raise_relay_id.data else: mod_pid.raise_relay_id = None mod_pid.raise_min_duration = ( form_mod_pid_relay.raise_min_duration.data ) mod_pid.raise_max_duration = ( form_mod_pid_relay.raise_max_duration.data ) mod_pid.raise_min_off_duration = ( form_mod_pid_relay.raise_min_off_duration.data ) if form_mod_pid_relay.lower_relay_id.data: mod_pid.lower_relay_id = form_mod_pid_relay.lower_relay_id.data else: mod_pid.lower_relay_id = None mod_pid.lower_min_duration = ( form_mod_pid_relay.lower_min_duration.data ) mod_pid.lower_max_duration = ( form_mod_pid_relay.lower_max_duration.data ) mod_pid.lower_min_off_duration = ( form_mod_pid_relay.lower_min_off_duration.data ) elif mod_pid.pid_type == "pwm": if not form_mod_pid_pwm.validate(): flash_form_errors(form_mod_pid_pwm) else: if form_mod_pid_relay.raise_relay_id.data: mod_pid.raise_relay_id = form_mod_pid_pwm.raise_relay_id.data else: mod_pid.raise_relay_id = None if form_mod_pid_relay.lower_relay_id.data: mod_pid.lower_relay_id = form_mod_pid_pwm.lower_relay_id.data else: mod_pid.lower_relay_id = None mod_pid.raise_min_duration = ( form_mod_pid_pwm.raise_min_duty_cycle.data ) mod_pid.raise_max_duration = ( form_mod_pid_pwm.raise_max_duty_cycle.data ) mod_pid.lower_min_duration = ( form_mod_pid_pwm.lower_min_duty_cycle.data ) mod_pid.lower_max_duration = ( form_mod_pid_pwm.lower_max_duty_cycle.data ) db.session.commit() # If the controller is active or paused, refresh variables in thread if mod_pid.is_activated: control = DaemonControl() return_value = control.pid_mod(form_mod_pid_base.pid_id.data) flash( gettext( "PID Controller settings refresh response: %(resp)s", resp=return_value, ), "success", ) except Exception as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for("page_routes.page_pid"))
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def has_required_pid_values(pid_id): pid = PID.query.filter(PID.id == pid_id).first() error = False if not pid.measurement: flash(gettext("A valid Measurement is required"), "error") error = True sensor_unique_id = pid.measurement.split(",")[0] sensor = Sensor.query.filter(Sensor.unique_id == sensor_unique_id).first() if not sensor: flash(gettext("A valid sensor is required"), "error") error = True if not pid.raise_relay_id and not pid.lower_relay_id: flash(gettext("A Raise Relay ID and/or a Lower Relay ID is required"), "error") error = True if error: return redirect("/pid")
def has_required_pid_values(pid_id): pid = PID.query.filter(PID.id == pid_id).first() error = False # TODO: Add more settings-checks before allowing controller to be activated if not pid.sensor_id: flash(gettext("A valid sensor is required"), "error") error = True if not pid.measurement: flash(gettext("A valid Measure Type is required"), "error") error = True if not pid.raise_relay_id and not pid.lower_relay_id: flash(gettext("A Raise Relay ID and/or a Lower Relay ID is required"), "error") error = True if error: return redirect("/pid")
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def pid_activate(pid_id): if has_required_pid_values(pid_id): return redirect(url_for("page_routes.page_pid")) action = "{action} {controller}".format( action=gettext("Actuate"), controller=gettext("PID") ) error = [] # Check if associated sensor is activated pid = PID.query.filter(PID.id == pid_id).first() sensor_unique_id = pid.measurement.split(",")[0] sensor = Sensor.query.filter(Sensor.unique_id == sensor_unique_id).first() if not sensor.is_activated: error.append( gettext( "Cannot activate PID controller if the associated sensor " "controller is inactive" ) ) if ( (pid.direction == "both" and not (pid.lower_relay_id and pid.raise_relay_id)) or (pid.direction == "lower" and not pid.lower_relay_id) or (pid.direction == "raise" and not pid.raise_relay_id) ): error.append( gettext( "Cannot activate PID controller if raise and/or lower relay IDs " "are not selected" ) ) if not error: # Signal the duration method can run because it's been # properly initiated (non-power failure) mod_method = Method.query.filter(Method.id == pid.method_id).first() if mod_method and mod_method.method_type == "Duration": mod_method.start_time = "Ready" db.session.commit() time.sleep(1) controller_activate_deactivate("activate", "PID", pid_id) flash_success_errors(error, action, url_for("page_routes.page_pid"))
def pid_activate(pid_id): if has_required_pid_values(pid_id): return redirect(url_for("page_routes.page_pid")) action = "{action} {controller}".format( action=gettext("Actuate"), controller=gettext("PID") ) error = [] # Check if associated sensor is activated pid = PID.query.filter(PID.id == pid_id).first() sensor = Sensor.query.filter(Sensor.id == pid.sensor_id).first() if not sensor.is_activated: error.append( gettext( "Cannot activate PID controller if the associated sensor " "controller is inactive" ) ) if ( (pid.direction == "both" and not (pid.lower_relay_id and pid.raise_relay_id)) or (pid.direction == "lower" and not pid.lower_relay_id) or (pid.direction == "raise" and not pid.raise_relay_id) ): error.append( gettext( "Cannot activate PID controller if raise and/or lower relay IDs " "are not selected" ) ) if not error: # Signal the duration method can run because it's been # properly initiated (non-power failure) mod_method = Method.query.filter(Method.id == pid.method_id).first() if mod_method and mod_method.method_type == "Duration": mod_method.start_time = "Ready" db.session.commit() time.sleep(1) controller_activate_deactivate("activate", "PID", pid_id) flash_success_errors(error, action, url_for("page_routes.page_pid"))
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def sensor_add(form_add_sensor): action = "{action} {controller}".format( action=gettext("Add"), controller=gettext("Sensor") ) error = [] if form_add_sensor.validate(): for _ in range(0, form_add_sensor.numberSensors.data): new_sensor = Sensor() new_sensor.device = form_add_sensor.sensor.data new_sensor.name = "{name} Sensor".format(name=form_add_sensor.sensor.data) if GPIO.RPI_INFO["P1_REVISION"] in [2, 3]: new_sensor.i2c_bus = 1 new_sensor.multiplexer_bus = 1 else: new_sensor.i2c_bus = 0 new_sensor.multiplexer_bus = 0 # Linux command as sensor if form_add_sensor.sensor.data == "LinuxCommand": new_sensor.cmd_command = "shuf -i 50-70 -n 1" new_sensor.cmd_measurement = "Condition" new_sensor.cmd_measurement_units = "unit" # Process monitors elif form_add_sensor.sensor.data == "MYCODO_RAM": new_sensor.measurements = "disk_space" new_sensor.location = "Mycodo_daemon" elif form_add_sensor.sensor.data == "RPi": new_sensor.measurements = "temperature" new_sensor.location = "RPi" elif form_add_sensor.sensor.data == "RPiCPULoad": new_sensor.measurements = "cpu_load_1m,cpu_load_5m,cpu_load_15m" new_sensor.location = "RPi" elif form_add_sensor.sensor.data == "RPiFreeSpace": new_sensor.measurements = "disk_space" new_sensor.location = "/" elif form_add_sensor.sensor.data == "EDGE": new_sensor.measurements = "edge" # Environmental Sensors # Temperature elif form_add_sensor.sensor.data in [ "ATLAS_PT1000_I2C", "ATLAS_PT1000_UART", "DS18B20", "TMP006", ]: new_sensor.measurements = "temperature" if form_add_sensor.sensor.data == "ATLAS_PT1000_I2C": new_sensor.interface = "I2C" new_sensor.location = "0x66" elif form_add_sensor.sensor.data == "ATLAS_PT1000_UART": new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" elif form_add_sensor.sensor.data == "TMP006": new_sensor.measurements = "temperature_object,temperature_die" new_sensor.location = "0x40" # Temperature/Humidity elif form_add_sensor.sensor.data in [ "AM2315", "DHT11", "DHT22", "HTU21D", "SHT1x_7x", "SHT2x", ]: new_sensor.measurements = "temperature,humidity,dewpoint" if form_add_sensor.sensor.data == "AM2315": new_sensor.location = "0x5c" elif form_add_sensor.sensor.data == "HTU21D": new_sensor.location = "0x40" elif form_add_sensor.sensor.data == "SHT2x": new_sensor.location = "0x40" # Chirp moisture sensor elif form_add_sensor.sensor.data == "CHIRP": new_sensor.measurements = "lux,moisture,temperature" new_sensor.location = "0x20" # CO2 elif form_add_sensor.sensor.data == "MH_Z16_I2C": new_sensor.measurements = "co2" new_sensor.location = "0x63" new_sensor.interface = "I2C" elif form_add_sensor.sensor.data in [ "K30_UART", "MH_Z16_UART", "MH_Z19_UART", ]: new_sensor.measurements = "co2" new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" # pH elif form_add_sensor.sensor.data == "ATLAS_PH_I2C": new_sensor.measurements = "ph" new_sensor.location = "0x63" new_sensor.interface = "I2C" elif form_add_sensor.sensor.data == "ATLAS_PH_UART": new_sensor.measurements = "ph" new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" # Pressure elif form_add_sensor.sensor.data in ["BME280", "BMP180", "BMP280"]: if form_add_sensor.sensor.data == "BME280": new_sensor.measurements = ( "temperature,humidity,dewpoint,pressure,altitude" ) new_sensor.location = "0x76" elif form_add_sensor.sensor.data in ["BMP180", "BMP280"]: new_sensor.measurements = "temperature,pressure,altitude" new_sensor.location = "0x77" # Light elif form_add_sensor.sensor.data in ["BH1750", "TSL2561", "TSL2591"]: new_sensor.measurements = "lux" if form_add_sensor.sensor.data == "BH1750": new_sensor.location = "0x23" new_sensor.resolution = 0 # 0=Low, 1=High, 2=High2 new_sensor.sensitivity = 69 elif form_add_sensor.sensor.data == "TSL2561": new_sensor.location = "0x39" elif form_add_sensor.sensor.data == "TSL2591": new_sensor.location = "0x29" # Analog to Digital Converters elif form_add_sensor.sensor.data in ["ADS1x15", "MCP342x"]: new_sensor.measurements = "voltage" if form_add_sensor.sensor.data == "ADS1x15": new_sensor.location = "0x48" new_sensor.adc_volts_min = -4.096 new_sensor.adc_volts_max = 4.096 elif form_add_sensor.sensor.data == "MCP342x": new_sensor.location = "0x68" new_sensor.adc_volts_min = -2.048 new_sensor.adc_volts_max = 2.048 try: new_sensor.save() display_order = csv_to_list_of_int(DisplayOrder.query.first().sensor) DisplayOrder.query.first().sensor = add_display_order( display_order, new_sensor.id ) db.session.commit() flash( gettext( "%(type)s Sensor with ID %(id)s (%(uuid)s) successfully added", type=form_add_sensor.sensor.data, id=new_sensor.id, uuid=new_sensor.unique_id, ), "success", ) except sqlalchemy.exc.OperationalError as except_msg: error.append(except_msg) except sqlalchemy.exc.IntegrityError as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for("page_routes.page_input")) else: flash_form_errors(form_add_sensor)
def sensor_add(form_add_sensor): action = "{action} {controller}".format( action=gettext("Add"), controller=gettext("Sensor") ) error = [] if form_add_sensor.validate(): for _ in range(0, form_add_sensor.numberSensors.data): new_sensor = Sensor() new_sensor.device = form_add_sensor.sensor.data new_sensor.name = "{name} Sensor".format(name=form_add_sensor.sensor.data) if GPIO.RPI_INFO["P1_REVISION"] in [2, 3]: new_sensor.i2c_bus = 1 new_sensor.multiplexer_bus = 1 else: new_sensor.i2c_bus = 0 new_sensor.multiplexer_bus = 0 # Process monitors if form_add_sensor.sensor.data == "MYCODO_RAM": new_sensor.measurements = "disk_space" new_sensor.location = "Mycodo_daemon" elif form_add_sensor.sensor.data == "RPi": new_sensor.measurements = "temperature" new_sensor.location = "RPi" elif form_add_sensor.sensor.data == "RPiCPULoad": new_sensor.measurements = "cpu_load_1m,cpu_load_5m,cpu_load_15m" new_sensor.location = "RPi" elif form_add_sensor.sensor.data == "RPiFreeSpace": new_sensor.measurements = "disk_space" new_sensor.location = "/" elif form_add_sensor.sensor.data == "EDGE": new_sensor.measurements = "edge" # Environmental Sensors # Temperature elif form_add_sensor.sensor.data in [ "ATLAS_PT1000_I2C", "ATLAS_PT1000_UART", "DS18B20", "TMP006", ]: new_sensor.measurements = "temperature" if form_add_sensor.sensor.data == "ATLAS_PT1000_I2C": new_sensor.interface = "I2C" new_sensor.location = "0x66" elif form_add_sensor.sensor.data == "ATLAS_PT1000_UART": new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" elif form_add_sensor.sensor.data == "TMP006": new_sensor.measurements = "temperature_object,temperature_die" new_sensor.location = "0x40" # Temperature/Humidity elif form_add_sensor.sensor.data in [ "AM2315", "DHT11", "DHT22", "HTU21D", "SHT1x_7x", "SHT2x", ]: new_sensor.measurements = "temperature,humidity,dewpoint" if form_add_sensor.sensor.data == "AM2315": new_sensor.location = "0x5c" elif form_add_sensor.sensor.data == "HTU21D": new_sensor.location = "0x40" elif form_add_sensor.sensor.data == "SHT2x": new_sensor.location = "0x40" # Chirp moisture sensor elif form_add_sensor.sensor.data == "CHIRP": new_sensor.measurements = "lux,moisture,temperature" new_sensor.location = "0x20" # CO2 elif form_add_sensor.sensor.data == "MH_Z16_I2C": new_sensor.measurements = "co2" new_sensor.location = "0x63" new_sensor.interface = "I2C" elif form_add_sensor.sensor.data in [ "K30_UART", "MH_Z16_UART", "MH_Z19_UART", ]: new_sensor.measurements = "co2" new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" # pH elif form_add_sensor.sensor.data == "ATLAS_PH_I2C": new_sensor.measurements = "ph" new_sensor.location = "0x63" new_sensor.interface = "I2C" elif form_add_sensor.sensor.data == "ATLAS_PH_UART": new_sensor.measurements = "ph" new_sensor.location = "Tx/Rx" new_sensor.interface = "UART" new_sensor.baud_rate = 9600 if GPIO.RPI_INFO["P1_REVISION"] == 3: new_sensor.device_loc = "/dev/ttyS0" else: new_sensor.device_loc = "/dev/ttyAMA0" # Pressure elif form_add_sensor.sensor.data in ["BME280", "BMP180", "BMP280"]: if form_add_sensor.sensor.data == "BME280": new_sensor.measurements = ( "temperature,humidity,dewpoint,pressure,altitude" ) new_sensor.location = "0x76" elif form_add_sensor.sensor.data in ["BMP180", "BMP280"]: new_sensor.measurements = "temperature,pressure,altitude" new_sensor.location = "0x77" # Light elif form_add_sensor.sensor.data in ["BH1750", "TSL2561", "TSL2591"]: new_sensor.measurements = "lux" if form_add_sensor.sensor.data == "BH1750": new_sensor.location = "0x23" new_sensor.resolution = 0 # 0=Low, 1=High, 2=High2 new_sensor.sensitivity = 69 elif form_add_sensor.sensor.data == "TSL2561": new_sensor.location = "0x39" elif form_add_sensor.sensor.data == "TSL2591": new_sensor.location = "0x29" # Analog to Digital Converters elif form_add_sensor.sensor.data in ["ADS1x15", "MCP342x"]: new_sensor.measurements = "voltage" if form_add_sensor.sensor.data == "ADS1x15": new_sensor.location = "0x48" new_sensor.adc_volts_min = -4.096 new_sensor.adc_volts_max = 4.096 elif form_add_sensor.sensor.data == "MCP342x": new_sensor.location = "0x68" new_sensor.adc_volts_min = -2.048 new_sensor.adc_volts_max = 2.048 try: new_sensor.save() display_order = csv_to_list_of_int(DisplayOrder.query.first().sensor) DisplayOrder.query.first().sensor = add_display_order( display_order, new_sensor.id ) db.session.commit() flash( gettext( "%(type)s Sensor with ID %(id)s (%(uuid)s) successfully added", type=form_add_sensor.sensor.data, id=new_sensor.id, uuid=new_sensor.unique_id, ), "success", ) except sqlalchemy.exc.OperationalError as except_msg: error.append(except_msg) except sqlalchemy.exc.IntegrityError as except_msg: error.append(except_msg) flash_success_errors(error, action, url_for("page_routes.page_input")) else: flash_form_errors(form_add_sensor)
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def sensor_deactivate_associated_controllers(sensor_id): sensor_unique_id = Sensor.query.filter(Sensor.id == sensor_id).first().unique_id pid = PID.query.filter(PID.is_activated == True).all() for each_pid in pid: if sensor_unique_id in each_pid.measurement: controller_activate_deactivate("deactivate", "PID", each_pid.id) lcd = LCD.query.filter(LCD.is_activated) for each_lcd in lcd: if sensor_id in [ each_lcd.line_1_sensor_id, each_lcd.line_2_sensor_id, each_lcd.line_3_sensor_id, each_lcd.line_4_sensor_id, ]: controller_activate_deactivate("deactivate", "LCD", each_lcd.id)
def sensor_deactivate_associated_controllers(sensor_id): pid = ( PID.query.filter(PID.sensor_id == sensor_id).filter(PID.is_activated == True) ).all() if pid: for each_pid in pid: controller_activate_deactivate("deactivate", "PID", each_pid.id) lcd = LCD.query.filter(LCD.is_activated) for each_lcd in lcd: if sensor_id in [ each_lcd.line_1_sensor_id, each_lcd.line_2_sensor_id, each_lcd.line_3_sensor_id, each_lcd.line_4_sensor_id, ]: controller_activate_deactivate("deactivate", "LCD", each_lcd.id)
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def page_graph(): """ Generate custom graphs to display sensor data retrieved from influxdb. """ # Create form objects form_add_graph = flaskforms.GraphAdd() form_add_gauge = flaskforms.GaugeAdd() form_mod_graph = flaskforms.GraphMod() form_mod_gauge = flaskforms.GaugeMod() form_del_graph = flaskforms.GraphDel() form_order_graph = flaskforms.GraphOrder() # Retrieve the order to display graphs display_order = csv_to_list_of_int(DisplayOrder.query.first().graph) # Retrieve tables from SQL database graph = Graph.query.all() pid = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() # Retrieve all choices to populate form drop-down menu pid_choices = flaskutils.choices_pids(pid) output_choices = flaskutils.choices_outputs(relay) sensor_choices = flaskutils.choices_sensors(sensor) # Add custom measurement and units to list (From linux command sensor) sensor_measurements = MEASUREMENT_UNITS sensor_measurements = add_custom_measurements( sensor, sensor_measurements, MEASUREMENT_UNITS ) # Add multi-select values as form choices, for validation form_mod_graph.pid_ids.choices = [] form_mod_graph.relay_ids.choices = [] form_mod_graph.sensor_ids.choices = [] for key, value in pid_choices.items(): form_mod_graph.pid_ids.choices.append((key, value)) for key, value in output_choices.items(): form_mod_graph.relay_ids.choices.append((key, value)) for key, value in sensor_choices.items(): form_mod_graph.sensor_ids.choices.append((key, value)) # Generate dictionary of custom colors for each graph colors_graph = dict_custom_colors() # Retrieve custom colors for gauges colors_gauge = OrderedDict() for each_graph in graph: if each_graph.range_colors: # Split into list color_areas = each_graph.range_colors.split(";") else: # Create empty list color_areas = [] total = [] if each_graph.graph_type == "gauge_angular": for each_range in color_areas: total.append( { "low": each_range.split(",")[0], "high": each_range.split(",")[1], "hex": each_range.split(",")[2], } ) elif each_graph.graph_type == "gauge_solid": for each_range in color_areas: total.append( {"stop": each_range.split(",")[0], "hex": each_range.split(",")[1]} ) colors_gauge.update({each_graph.id: total}) # Detect which form on the page was submitted if request.method == "POST": if not flaskutils.user_has_permission("edit_controllers"): return redirect(url_for("general_routes.home")) form_name = request.form["form-name"] if form_name == "modGraph": flaskutils.graph_mod(form_mod_graph, request.form) elif form_name == "modGauge": flaskutils.graph_mod(form_mod_gauge, request.form) elif form_name == "delGraph": flaskutils.graph_del(form_del_graph) elif form_order_graph.orderGraphUp.data: flaskutils.graph_reorder( form_order_graph.orderGraph_id.data, display_order, "up" ) elif form_order_graph.orderGraphDown.data: flaskutils.graph_reorder( form_order_graph.orderGraph_id.data, display_order, "down" ) elif form_name == "addGraph": flaskutils.graph_add(form_add_graph, display_order) elif form_name == "addGauge": flaskutils.graph_add(form_add_gauge, display_order) return redirect("/graph") return render_template( "pages/graph.html", graph=graph, pid=pid, relay=relay, sensor=sensor, pid_choices=pid_choices, output_choices=output_choices, sensor_choices=sensor_choices, colors_graph=colors_graph, colors_gauge=colors_gauge, sensor_measurements=sensor_measurements, measurement_units=MEASUREMENT_UNITS, displayOrder=display_order, form_mod_graph=form_mod_graph, form_mod_gauge=form_mod_gauge, form_del_graph=form_del_graph, form_order_graph=form_order_graph, form_add_graph=form_add_graph, form_add_gauge=form_add_gauge, )
def page_graph(): """ Generate custom graphs to display sensor data retrieved from influxdb. """ # Create form objects form_add_graph = flaskforms.GraphAdd() form_add_gauge = flaskforms.GaugeAdd() form_mod_graph = flaskforms.GraphMod() form_mod_gauge = flaskforms.GaugeMod() form_del_graph = flaskforms.GraphDel() form_order_graph = flaskforms.GraphOrder() # Retrieve the order to display graphs display_order = csv_to_list_of_int(DisplayOrder.query.first().graph) # Retrieve tables from SQL database graph = Graph.query.all() pid = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() # Retrieve all choices to populate form drop-down menu pid_choices = flaskutils.choices_pids(pid) output_choices = flaskutils.choices_outputs(relay) sensor_choices = flaskutils.choices_sensors(sensor) # Add multi-select values as form choices, for validation form_mod_graph.pid_ids.choices = [] form_mod_graph.relay_ids.choices = [] form_mod_graph.sensor_ids.choices = [] for key, value in pid_choices.items(): form_mod_graph.pid_ids.choices.append((key, value)) for key, value in output_choices.items(): form_mod_graph.relay_ids.choices.append((key, value)) for key, value in sensor_choices.items(): form_mod_graph.sensor_ids.choices.append((key, value)) # Generate dictionary of custom colors for each graph colors_graph = dict_custom_colors() # Retrieve custom colors for gauges colors_gauge = OrderedDict() for each_graph in graph: if each_graph.range_colors: # Split into list color_areas = each_graph.range_colors.split(";") else: # Create empty list color_areas = [] total = [] if each_graph.graph_type == "gauge_angular": for each_range in color_areas: total.append( { "low": each_range.split(",")[0], "high": each_range.split(",")[1], "hex": each_range.split(",")[2], } ) elif each_graph.graph_type == "gauge_solid": for each_range in color_areas: total.append( {"stop": each_range.split(",")[0], "hex": each_range.split(",")[1]} ) colors_gauge.update({each_graph.id: total}) # Detect which form on the page was submitted if request.method == "POST": if not flaskutils.user_has_permission("edit_controllers"): return redirect(url_for("general_routes.home")) form_name = request.form["form-name"] if form_name == "modGraph": flaskutils.graph_mod(form_mod_graph, request.form) elif form_name == "modGauge": flaskutils.graph_mod(form_mod_gauge, request.form) elif form_name == "delGraph": flaskutils.graph_del(form_del_graph) elif form_order_graph.orderGraphUp.data: flaskutils.graph_reorder( form_order_graph.orderGraph_id.data, display_order, "up" ) elif form_order_graph.orderGraphDown.data: flaskutils.graph_reorder( form_order_graph.orderGraph_id.data, display_order, "down" ) elif form_name == "addGraph": flaskutils.graph_add(form_add_graph, display_order) elif form_name == "addGauge": flaskutils.graph_add(form_add_gauge, display_order) return redirect("/graph") return render_template( "pages/graph.html", graph=graph, pid=pid, relay=relay, sensor=sensor, pid_choices=pid_choices, output_choices=output_choices, sensor_choices=sensor_choices, colors_graph=colors_graph, colors_gauge=colors_gauge, measurement_units=MEASUREMENT_UNITS, displayOrder=display_order, form_mod_graph=form_mod_graph, form_mod_gauge=form_mod_gauge, form_del_graph=form_del_graph, form_order_graph=form_order_graph, form_add_graph=form_add_graph, form_add_gauge=form_add_gauge, )
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def page_lcd(): """Display LCD output settings""" lcd = LCD.query.all() pid = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() display_order = csv_to_list_of_int(DisplayOrder.query.first().lcd) form_add_lcd = flaskforms.LCDAdd() form_mod_lcd = flaskforms.LCDMod() measurements = MEASUREMENTS # Add custom measurement and units to list (From linux command sensor) for each_sensor in sensor: if ( each_sensor.cmd_measurement and each_sensor.cmd_measurement not in MEASUREMENTS ): if each_sensor.cmd_measurement and each_sensor.cmd_measurement_units: measurements.update({"LinuxCommand": [each_sensor.cmd_measurement]}) if request.method == "POST": if not flaskutils.user_has_permission("edit_controllers"): return redirect(url_for("general_routes.home")) if form_add_lcd.add.data: flaskutils.lcd_add(form_add_lcd.quantity.data) elif form_mod_lcd.save.data: flaskutils.lcd_mod(form_mod_lcd) elif form_mod_lcd.delete.data: flaskutils.lcd_del(form_mod_lcd.lcd_id.data) elif form_mod_lcd.reorder_up.data: flaskutils.lcd_reorder(form_mod_lcd.lcd_id.data, display_order, "up") elif form_mod_lcd.reorder_down.data: flaskutils.lcd_reorder(form_mod_lcd.lcd_id.data, display_order, "down") elif form_mod_lcd.activate.data: flaskutils.lcd_activate(form_mod_lcd.lcd_id.data) elif form_mod_lcd.deactivate.data: flaskutils.lcd_deactivate(form_mod_lcd.lcd_id.data) elif form_mod_lcd.reset_flashing.data: flaskutils.lcd_reset_flashing(form_mod_lcd.lcd_id.data) return redirect("/lcd") return render_template( "pages/lcd.html", lcd=lcd, measurements=measurements, pid=pid, relay=relay, sensor=sensor, displayOrder=display_order, form_add_lcd=form_add_lcd, form_mod_lcd=form_mod_lcd, )
def page_lcd(): """Display LCD output settings""" lcd = LCD.query.all() pid = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() display_order = csv_to_list_of_int(DisplayOrder.query.first().lcd) form_add_lcd = flaskforms.LCDAdd() form_mod_lcd = flaskforms.LCDMod() if request.method == "POST": if not flaskutils.user_has_permission("edit_controllers"): return redirect(url_for("general_routes.home")) if form_add_lcd.add.data: flaskutils.lcd_add(form_add_lcd.quantity.data) elif form_mod_lcd.save.data: flaskutils.lcd_mod(form_mod_lcd) elif form_mod_lcd.delete.data: flaskutils.lcd_del(form_mod_lcd.lcd_id.data) elif form_mod_lcd.reorder_up.data: flaskutils.lcd_reorder(form_mod_lcd.lcd_id.data, display_order, "up") elif form_mod_lcd.reorder_down.data: flaskutils.lcd_reorder(form_mod_lcd.lcd_id.data, display_order, "down") elif form_mod_lcd.activate.data: flaskutils.lcd_activate(form_mod_lcd.lcd_id.data) elif form_mod_lcd.deactivate.data: flaskutils.lcd_deactivate(form_mod_lcd.lcd_id.data) elif form_mod_lcd.reset_flashing.data: flaskutils.lcd_reset_flashing(form_mod_lcd.lcd_id.data) return redirect("/lcd") return render_template( "pages/lcd.html", lcd=lcd, measurements=MEASUREMENTS, pid=pid, relay=relay, sensor=sensor, displayOrder=display_order, form_add_lcd=form_add_lcd, form_mod_lcd=form_mod_lcd, )
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def page_pid(): """Display PID settings""" method = Method.query.all() pids = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() sensor_choices = flaskutils.choices_sensors(sensor) display_order = csv_to_list_of_int(DisplayOrder.query.first().pid) form_add_pid = flaskforms.PIDAdd() form_mod_pid_base = flaskforms.PIDModBase() form_mod_pid_relay = flaskforms.PIDModRelay() form_mod_pid_pwm = flaskforms.PIDModPWM() # Create list of file names from the pid_options directory # Used in generating the correct options for each PID pid_templates = [] pid_path = os.path.join( INSTALL_DIRECTORY, "mycodo/mycodo_flask/templates/pages/pid_options" ) for _, _, file_names in os.walk(pid_path): pid_templates.extend(file_names) break if request.method == "POST": if not flaskutils.user_has_permission("edit_controllers"): return redirect(url_for("general_routes.home")) form_name = request.form["form-name"] if form_name == "addPID": flaskutils.pid_add(form_add_pid) elif form_name == "modPID": if form_mod_pid_base.save.data: flaskutils.pid_mod( form_mod_pid_base, form_mod_pid_pwm, form_mod_pid_relay ) elif form_mod_pid_base.delete.data: flaskutils.pid_del(form_mod_pid_base.pid_id.data) elif form_mod_pid_base.reorder_up.data: flaskutils.pid_reorder( form_mod_pid_base.pid_id.data, display_order, "up" ) elif form_mod_pid_base.reorder_down.data: flaskutils.pid_reorder( form_mod_pid_base.pid_id.data, display_order, "down" ) elif form_mod_pid_base.activate.data: flaskutils.pid_activate(form_mod_pid_base.pid_id.data) elif form_mod_pid_base.deactivate.data: flaskutils.pid_deactivate(form_mod_pid_base.pid_id.data) elif form_mod_pid_base.hold.data: flaskutils.pid_manipulate(form_mod_pid_base.pid_id.data, "Hold") elif form_mod_pid_base.pause.data: flaskutils.pid_manipulate(form_mod_pid_base.pid_id.data, "Pause") elif form_mod_pid_base.resume.data: flaskutils.pid_manipulate(form_mod_pid_base.pid_id.data, "Resume") return redirect("/pid") return render_template( "pages/pid.html", method=method, pids=pids, pid_templates=pid_templates, relay=relay, sensor=sensor, sensor_choices=sensor_choices, displayOrder=display_order, form_add_pid=form_add_pid, form_mod_pid_base=form_mod_pid_base, form_mod_pid_pwm=form_mod_pid_pwm, form_mod_pid_relay=form_mod_pid_relay, )
def page_pid(): """Display PID settings""" pids = PID.query.all() relay = Relay.query.all() sensor = Sensor.query.all() display_order = csv_to_list_of_int(DisplayOrder.query.first().pid) form_add_pid = flaskforms.PIDAdd() form_mod_pid_base = flaskforms.PIDModBase() form_mod_pid_relay = flaskforms.PIDModRelay() form_mod_pid_pwm = flaskforms.PIDModPWM() method = Method.query.all() # Create list of file names from the pid_options directory # Used in generating the correct options for each PID pid_templates = [] pid_path = os.path.join( INSTALL_DIRECTORY, "mycodo/mycodo_flask/templates/pages/pid_options" ) for _, _, file_names in os.walk(pid_path): pid_templates.extend(file_names) break if request.method == "POST": if not flaskutils.user_has_permission("edit_controllers"): return redirect(url_for("general_routes.home")) form_name = request.form["form-name"] if form_name == "addPID": flaskutils.pid_add(form_add_pid) elif form_name == "modPID": if form_mod_pid_base.save.data: flaskutils.pid_mod( form_mod_pid_base, form_mod_pid_pwm, form_mod_pid_relay ) elif form_mod_pid_base.delete.data: flaskutils.pid_del(form_mod_pid_base.pid_id.data) elif form_mod_pid_base.reorder_up.data: flaskutils.pid_reorder( form_mod_pid_base.pid_id.data, display_order, "up" ) elif form_mod_pid_base.reorder_down.data: flaskutils.pid_reorder( form_mod_pid_base.pid_id.data, display_order, "down" ) elif form_mod_pid_base.activate.data: flaskutils.pid_activate(form_mod_pid_base.pid_id.data) elif form_mod_pid_base.deactivate.data: flaskutils.pid_deactivate(form_mod_pid_base.pid_id.data) elif form_mod_pid_base.hold.data: flaskutils.pid_manipulate(form_mod_pid_base.pid_id.data, "Hold") elif form_mod_pid_base.pause.data: flaskutils.pid_manipulate(form_mod_pid_base.pid_id.data, "Pause") elif form_mod_pid_base.resume.data: flaskutils.pid_manipulate(form_mod_pid_base.pid_id.data, "Resume") return redirect("/pid") return render_template( "pages/pid.html", method=method, pids=pids, pid_templates=pid_templates, relay=relay, sensor=sensor, displayOrder=display_order, form_add_pid=form_add_pid, form_mod_pid_base=form_mod_pid_base, form_mod_pid_pwm=form_mod_pid_pwm, form_mod_pid_relay=form_mod_pid_relay, )
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def get_measurement(self): """Determine if the return value of the command is a number""" out, _, _ = cmd_output(self.command) if str_is_float(out): return float(out) else: return None
def get_measurement(self): """Determine if the return value of the command is a number""" out, err, status = cmd_output(self.command) if str_is_float(out): return float(out) else: return None
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def __init__(self, address, bus): super(TSL2591Sensor, self).__init__() self.logger = logging.getLogger( "mycodo.sensors.tsl2591_{bus}_{add}".format(bus=bus, add=address) ) self.i2c_address = address self.i2c_bus = bus self._lux = 0.0 self.tsl = tsl2591.Tsl2591(i2c_bus=self.i2c_bus, sensor_address=self.i2c_address)
def __init__(self, address, bus): super(TSL2591Sensor, self).__init__() self.logger = logging.getLogger( "mycodo.sensors.tsl2591_{bus}_{add}".format(bus=bus, add=address) ) self.i2c_address = address self.i2c_bus = bus self._lux = 0.0
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def get_measurement(self): """Gets the TSL2591's lux""" full, ir = ( self.tsl.get_full_luminosity() ) # read raw values (full spectrum and ir spectrum) lux = self.tsl.calculate_lux(full, ir) # convert raw values to lux return lux
def get_measurement(self): """Gets the TSL2591's lux""" tsl = tsl2591.Tsl2591(i2c_bus=self.i2c_bus, sensor_address=self.i2c_address) full, ir = ( tsl.get_full_luminosity() ) # read raw values (full spectrum and ir spectrum) lux = tsl.calculate_lux(full, ir) # convert raw values to lux return lux
https://github.com/kizniche/Mycodo/issues/254
2017-06-07 11:03:18,941 - mycodo.sensors.raspi - ERROR - RaspberryPiCPUTemp.get_measurement() method raised IOError: [Errno 24] Too many open files: '/sys/class/thermal/thermal_zone0/temp' 2017-06-07 11:03:20,138 - mycodo.pid_1 - ERROR - Run Error: (sqlite3.OperationalError) unable to open database file ========= Remote Traceback (1) ========= Traceback (most recent call last): File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 329, in _dispatch_request File "/var/www/mycodo/env/local/lib/python2.7/site-packages/rpyc/core/protocol.py", line 583, in _handle_call File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 201, in exposed_relay_off File "/var/www/mycodo/mycodo/mycodo_daemon.py", line 553, in relay_off File "/var/www/mycodo/mycodo/controller_relay.py", line 348, in relay_on_off self.check_conditionals(relay_id, duration) File "/var/www/mycodo/mycodo/controller_relay.py", line 397, in check_conditionals for each_conditional in conditionals.all():
IOError
def read(self): data, bad_format = None, False try: data = json.loads(self.file.read_text()) logging.debug("got {} from %s".format(self.msg), *self.msg_args) return data except ValueError: bad_format = True except Exception: # noqa pass if bad_format: try: self.remove() except ( OSError ): # reading and writing on the same file may cause race on multiple processes pass return None
def read(self): data, bad_format = None, False try: data = json.loads(self.file.read_text()) logging.debug("got {} from %s".format(self.msg), *self.msg_args) return data except ValueError: bad_format = True except Exception: # noqa pass if bad_format: self.remove() return None
https://github.com/pypa/virtualenv/issues/1938
Traceback (most recent call last): File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 94, in _get do_periodic_update=self.periodic_update, File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\wheels\acquire.py", line 25, in get_wheel wheel = from_bundle(distribution, version, for_py_version, search_dirs, app_data, do_periodic_update) File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\wheels\bundle.py", line 20, in from_bundle wheel = periodic_update(distribution, for_py_version, wheel, search_dirs, app_data, do_periodic_update) File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 41, in periodic_update handle_auto_update(distribution, for_py_version, wheel, search_dirs, app_data) File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\seed\wheels\periodic_update.py", line 62, in handle_auto_update u_log = UpdateLog.from_dict(embed_update_log.read()) File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\app_data\via_disk_folder.py", line 140, in read self.remove() File "C:\Users\runneradmin\.virtualenvs\pipenv-6Kr0DpZ2\lib\site-packages\virtualenv\app_data\via_disk_folder.py", line 144, in remove self.file.unlink() File "C:\hostedtoolcache\windows\Python\3.6.8\x64\lib\pathlib.py", line 1284, in unlink self._accessor.unlink(self) File "C:\hostedtoolcache\windows\Python\3.6.8\x64\lib\pathlib.py", line 387, in wrapped return strfunc(str(pathobj), *args) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\runneradmin\\AppData\\Local\\pypa\\virtualenv\\wheel\\3.8\\embed\\1\\wheel.json' PermissionError(13, 'The process cannot access the file because it is being used by another process') RuntimeError: seed failed due to failing to download wheels wheel
PermissionError
def generate_draft_news(): root = Path(__file__).parents[1] new = subprocess.check_output( [sys.executable, "-m", "towncrier", "--draft", "--version", "NEXT"], cwd=root, universal_newlines=True, ) (root / "docs" / "_draft.rst").write_text( "" if "No significant changes" in new else new )
def generate_draft_news(): root = Path(__file__).parents[1] exe = Path(sys.executable) towncrier = exe.with_name("towncrier{}".format(exe.suffix)) new = subprocess.check_output( [str(towncrier), "--draft", "--version", "NEXT"], cwd=root, universal_newlines=True, ) (root / "docs" / "_draft.rst").write_text( "" if "No significant changes" in new else new )
https://github.com/pypa/virtualenv/issues/1847
$ sphinx-build docs out Running Sphinx v2.4.4 Configuration error: There is a programmable error in your configuration file: Traceback (most recent call last): File "/usr/lib/python3.8/site-packages/sphinx/config.py", line 348, in eval_config_file execfile_(filename, namespace) File "/usr/lib/python3.8/site-packages/sphinx/util/pycompat.py", line 81, in execfile_ exec(code, _globals) File "/tmp/virtualenv/docs/conf.py", line 68, in <module> generate_draft_news() File "/tmp/virtualenv/docs/conf.py", line 64, in generate_draft_news new = subprocess.check_output([str(towncrier), "--draft", "--version", "NEXT"], cwd=root, universal_newlines=True) File "/usr/lib/python3.8/subprocess.py", line 411, in check_output return run(*popenargs, stdout=PIPE, timeout=timeout, check=True, File "/usr/lib/python3.8/subprocess.py", line 489, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.8/subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib/python3.8/subprocess.py", line 1702, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/usr/bin/towncrier.8'
FileNotFoundError
def run(): """print debug data about the virtual environment""" try: from collections import OrderedDict except ImportError: # pragma: no cover # this is possible if the standard library cannot be accessed # noinspection PyPep8Naming OrderedDict = dict # pragma: no cover result = OrderedDict([("sys", OrderedDict())]) path_keys = ( "executable", "_base_executable", "prefix", "base_prefix", "real_prefix", "exec_prefix", "base_exec_prefix", "path", "meta_path", ) for key in path_keys: value = getattr(sys, key, None) if isinstance(value, list): value = encode_list_path(value) else: value = encode_path(value) result["sys"][key] = value result["sys"]["fs_encoding"] = sys.getfilesystemencoding() result["sys"]["io_encoding"] = getattr(sys.stdout, "encoding", None) result["version"] = sys.version try: import sysconfig # https://bugs.python.org/issue22199 makefile = getattr( sysconfig, "get_makefile_filename", getattr(sysconfig, "_get_makefile_filename", None), ) result["makefile_filename"] = encode_path(makefile()) except ImportError: pass import os # landmark result["os"] = repr(os) try: # noinspection PyUnresolvedReferences import site # site result["site"] = repr(site) except ImportError as exception: # pragma: no cover result["site"] = repr(exception) # pragma: no cover try: # noinspection PyUnresolvedReferences import datetime # site result["datetime"] = repr(datetime) except ImportError as exception: # pragma: no cover result["datetime"] = repr(exception) # pragma: no cover try: # noinspection PyUnresolvedReferences import math # site result["math"] = repr(math) except ImportError as exception: # pragma: no cover result["math"] = repr(exception) # pragma: no cover # try to print out, this will validate if other core modules are available (json in this case) try: import json result["json"] = repr(json) except ImportError as exception: result["json"] = repr(exception) else: try: content = json.dumps(result, indent=2) sys.stdout.write(content) except (ValueError, TypeError) as exception: # pragma: no cover sys.stderr.write(repr(exception)) sys.stdout.write(repr(result)) # pragma: no cover raise SystemExit(1) # pragma: no cover
def run(): """print debug data about the virtual environment""" try: from collections import OrderedDict except ImportError: # pragma: no cover # this is possible if the standard library cannot be accessed # noinspection PyPep8Naming OrderedDict = dict # pragma: no cover result = OrderedDict([("sys", OrderedDict())]) path_keys = ( "executable", "_base_executable", "prefix", "base_prefix", "real_prefix", "exec_prefix", "base_exec_prefix", "path", "meta_path", ) for key in path_keys: value = getattr(sys, key, None) if isinstance(value, list): value = encode_list_path(value) else: value = encode_path(value) result["sys"][key] = value result["sys"]["fs_encoding"] = sys.getfilesystemencoding() result["sys"]["io_encoding"] = getattr(sys.stdout, "encoding", None) result["version"] = sys.version try: import sysconfig result["makefile_filename"] = encode_path(sysconfig.get_makefile_filename()) except ImportError: pass import os # landmark result["os"] = repr(os) try: # noinspection PyUnresolvedReferences import site # site result["site"] = repr(site) except ImportError as exception: # pragma: no cover result["site"] = repr(exception) # pragma: no cover try: # noinspection PyUnresolvedReferences import datetime # site result["datetime"] = repr(datetime) except ImportError as exception: # pragma: no cover result["datetime"] = repr(exception) # pragma: no cover try: # noinspection PyUnresolvedReferences import math # site result["math"] = repr(math) except ImportError as exception: # pragma: no cover result["math"] = repr(exception) # pragma: no cover # try to print out, this will validate if other core modules are available (json in this case) try: import json result["json"] = repr(json) except ImportError as exception: result["json"] = repr(exception) else: try: content = json.dumps(result, indent=2) sys.stdout.write(content) except (ValueError, TypeError) as exception: # pragma: no cover sys.stderr.write(repr(exception)) sys.stdout.write(repr(result)) # pragma: no cover raise SystemExit(1) # pragma: no cover
https://github.com/pypa/virtualenv/issues/1810
-bash-4.2# virtualenv --version Traceback (most recent call last): File "/usr/bin/virtualenv", line 5, in <module> from virtualenv.__main__ import run_with_catch File "/usr/lib/python2.7/site-packages/virtualenv/__init__.py", line 3, in <module> from .run import cli_run File "/usr/lib/python2.7/site-packages/virtualenv/run/__init__.py", line 12, in <module> from .plugin.creators import CreatorSelector File "/usr/lib/python2.7/site-packages/virtualenv/run/plugin/creators.py", line 6, in <module> from virtualenv.create.via_global_ref.builtin.builtin_way import VirtualenvBuiltin File "/usr/lib/python2.7/site-packages/virtualenv/create/via_global_ref/builtin/builtin_way.py", line 7, in <module> from virtualenv.create.creator import Creator File "/usr/lib/python2.7/site-packages/virtualenv/create/creator.py", line 14, in <module> from virtualenv.discovery.cached_py_info import LogCmd File "/usr/lib/python2.7/site-packages/virtualenv/discovery/cached_py_info.py", line 26, in <module> _CACHE[Path(sys.executable)] = PythonInfo() File "/usr/lib/python2.7/site-packages/virtualenv/discovery/py_info.py", line 82, in __init__ ("makefile_filename", sysconfig.get_makefile_filename()), AttributeError: 'module' object has no attribute 'get_makefile_filename'
AttributeError
def __init__(self): def u(v): return v.decode("utf-8") if isinstance(v, bytes) else v def abs_path(v): return ( None if v is None else os.path.abspath(v) ) # unroll relative elements from path (e.g. ..) # qualifies the python self.platform = u(sys.platform) self.implementation = u(platform.python_implementation()) if self.implementation == "PyPy": self.pypy_version_info = tuple(u(i) for i in sys.pypy_version_info) # this is a tuple in earlier, struct later, unify to our own named tuple self.version_info = VersionInfo(*list(u(i) for i in sys.version_info)) self.architecture = 64 if sys.maxsize > 2**32 else 32 self.version = u(sys.version) self.os = u(os.name) # information about the prefix - determines python home self.prefix = u(abs_path(getattr(sys, "prefix", None))) # prefix we think self.base_prefix = u(abs_path(getattr(sys, "base_prefix", None))) # venv self.real_prefix = u(abs_path(getattr(sys, "real_prefix", None))) # old virtualenv # information about the exec prefix - dynamic stdlib modules self.base_exec_prefix = u(abs_path(getattr(sys, "base_exec_prefix", None))) self.exec_prefix = u(abs_path(getattr(sys, "exec_prefix", None))) self.executable = u(abs_path(sys.executable)) # the executable we were invoked via self.original_executable = u( abs_path(self.executable) ) # the executable as known by the interpreter self.system_executable = ( self._fast_get_system_executable() ) # the executable we are based of (if available) try: __import__("venv") has = True except ImportError: has = False self.has_venv = has self.path = [u(i) for i in sys.path] self.file_system_encoding = u(sys.getfilesystemencoding()) self.stdout_encoding = u(getattr(sys.stdout, "encoding", None)) self.sysconfig_paths = { u(i): u(sysconfig.get_path(i, expand=False)) for i in sysconfig.get_path_names() } # https://bugs.python.org/issue22199 makefile = getattr( sysconfig, "get_makefile_filename", getattr(sysconfig, "_get_makefile_filename", None), ) self.sysconfig = { u(k): u(v) for k, v in [ # a list of content to store from sysconfig ("makefile_filename", makefile()), ] if k is not None } config_var_keys = set() for element in self.sysconfig_paths.values(): for k in _CONF_VAR_RE.findall(element): config_var_keys.add(u(k[1:-1])) config_var_keys.add("PYTHONFRAMEWORK") self.sysconfig_vars = { u(i): u(sysconfig.get_config_var(i) or "") for i in config_var_keys } if self.implementation == "PyPy" and sys.version_info.major == 2: self.sysconfig_vars["implementation_lower"] = "python" self.distutils_install = {u(k): u(v) for k, v in self._distutils_install().items()} confs = { k: (self.system_prefix if v.startswith(self.prefix) else v) for k, v in self.sysconfig_vars.items() } self.system_stdlib = self.sysconfig_path("stdlib", confs) self.system_stdlib_platform = self.sysconfig_path("platstdlib", confs) self.max_size = getattr(sys, "maxsize", getattr(sys, "maxint", None)) self._creators = None
def __init__(self): def u(v): return v.decode("utf-8") if isinstance(v, bytes) else v def abs_path(v): return ( None if v is None else os.path.abspath(v) ) # unroll relative elements from path (e.g. ..) # qualifies the python self.platform = u(sys.platform) self.implementation = u(platform.python_implementation()) if self.implementation == "PyPy": self.pypy_version_info = tuple(u(i) for i in sys.pypy_version_info) # this is a tuple in earlier, struct later, unify to our own named tuple self.version_info = VersionInfo(*list(u(i) for i in sys.version_info)) self.architecture = 64 if sys.maxsize > 2**32 else 32 self.version = u(sys.version) self.os = u(os.name) # information about the prefix - determines python home self.prefix = u(abs_path(getattr(sys, "prefix", None))) # prefix we think self.base_prefix = u(abs_path(getattr(sys, "base_prefix", None))) # venv self.real_prefix = u(abs_path(getattr(sys, "real_prefix", None))) # old virtualenv # information about the exec prefix - dynamic stdlib modules self.base_exec_prefix = u(abs_path(getattr(sys, "base_exec_prefix", None))) self.exec_prefix = u(abs_path(getattr(sys, "exec_prefix", None))) self.executable = u(abs_path(sys.executable)) # the executable we were invoked via self.original_executable = u( abs_path(self.executable) ) # the executable as known by the interpreter self.system_executable = ( self._fast_get_system_executable() ) # the executable we are based of (if available) try: __import__("venv") has = True except ImportError: has = False self.has_venv = has self.path = [u(i) for i in sys.path] self.file_system_encoding = u(sys.getfilesystemencoding()) self.stdout_encoding = u(getattr(sys.stdout, "encoding", None)) self.sysconfig_paths = { u(i): u(sysconfig.get_path(i, expand=False)) for i in sysconfig.get_path_names() } self.sysconfig = { u(k): u(v) for k, v in [ # a list of content to store from sysconfig ("makefile_filename", sysconfig.get_makefile_filename()), ] if k is not None } config_var_keys = set() for element in self.sysconfig_paths.values(): for k in _CONF_VAR_RE.findall(element): config_var_keys.add(u(k[1:-1])) config_var_keys.add("PYTHONFRAMEWORK") self.sysconfig_vars = { u(i): u(sysconfig.get_config_var(i) or "") for i in config_var_keys } if self.implementation == "PyPy" and sys.version_info.major == 2: self.sysconfig_vars["implementation_lower"] = "python" self.distutils_install = {u(k): u(v) for k, v in self._distutils_install().items()} confs = { k: (self.system_prefix if v.startswith(self.prefix) else v) for k, v in self.sysconfig_vars.items() } self.system_stdlib = self.sysconfig_path("stdlib", confs) self.system_stdlib_platform = self.sysconfig_path("platstdlib", confs) self.max_size = getattr(sys, "maxsize", getattr(sys, "maxint", None)) self._creators = None
https://github.com/pypa/virtualenv/issues/1810
-bash-4.2# virtualenv --version Traceback (most recent call last): File "/usr/bin/virtualenv", line 5, in <module> from virtualenv.__main__ import run_with_catch File "/usr/lib/python2.7/site-packages/virtualenv/__init__.py", line 3, in <module> from .run import cli_run File "/usr/lib/python2.7/site-packages/virtualenv/run/__init__.py", line 12, in <module> from .plugin.creators import CreatorSelector File "/usr/lib/python2.7/site-packages/virtualenv/run/plugin/creators.py", line 6, in <module> from virtualenv.create.via_global_ref.builtin.builtin_way import VirtualenvBuiltin File "/usr/lib/python2.7/site-packages/virtualenv/create/via_global_ref/builtin/builtin_way.py", line 7, in <module> from virtualenv.create.creator import Creator File "/usr/lib/python2.7/site-packages/virtualenv/create/creator.py", line 14, in <module> from virtualenv.discovery.cached_py_info import LogCmd File "/usr/lib/python2.7/site-packages/virtualenv/discovery/cached_py_info.py", line 26, in <module> _CACHE[Path(sys.executable)] = PythonInfo() File "/usr/lib/python2.7/site-packages/virtualenv/discovery/py_info.py", line 82, in __init__ ("makefile_filename", sysconfig.get_makefile_filename()), AttributeError: 'module' object has no attribute 'get_makefile_filename'
AttributeError
def find_spec(self, fullname, path, target=None): if fullname in _DISTUTILS_PATCH and self.fullname is None: with self.lock: self.fullname = fullname try: spec = find_spec(fullname, path) if spec is not None: # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work is_new_api = hasattr(spec.loader, "exec_module") func_name = "exec_module" if is_new_api else "load_module" old = getattr(spec.loader, func_name) func = self.exec_module if is_new_api else self.load_module if old is not func: try: setattr(spec.loader, func_name, partial(func, old)) except AttributeError: pass # C-Extension loaders are r/o such as zipimporter with <python 3.7 return spec finally: self.fullname = None
def find_spec(self, fullname, path, target=None): if fullname in _DISTUTILS_PATCH and self.fullname is None: with self.lock: self.fullname = fullname try: spec = find_spec(fullname, path) if spec is not None: # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work is_new_api = hasattr(spec.loader, "exec_module") func_name = "exec_module" if is_new_api else "load_module" old = getattr(spec.loader, func_name) func = self.exec_module if is_new_api else self.load_module if old is not func: setattr(spec.loader, func_name, partial(func, old)) return spec finally: self.fullname = None
https://github.com/pypa/virtualenv/issues/1715
import setuptools Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 656, in _load_unlocked File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible File "/tmp/test/setuptools-42.0.0/setuptools-42.0.0-py3.6.egg/setuptools/__init__.py", line 20, in <module> File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 951, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 894, in _find_spec File "/tmp/salt-tests-tmpdir/tmp8v5ucrk2/psetuptools/lib/python3.6/site-packages/_virtualenv.py", line 64, in find_spec setattr(spec.loader, func_name, partial(func, old)) AttributeError: 'zipimport.zipimporter' object attribute 'load_module' is read-only
AttributeError
def _run_parser(self, class_n, key, name): test_name = {"creator": "can_create", "activators": "supports"} func_name = test_name.get(key) try: if func_name is not None: prev = getattr(class_n, func_name) def a(*args, **kwargs): prev(*args, **kwargs) if key == "activators": return True elif key == "creator": if name == "venv": from virtualenv.create.via_global_ref.venv import ( ViaGlobalRefMeta, ) meta = ViaGlobalRefMeta() meta.symlink_error = None return meta from virtualenv.create.via_global_ref.builtin.via_global_self_do import ( BuiltinViaGlobalRefMeta, ) meta = BuiltinViaGlobalRefMeta() meta.symlink_error = None return meta raise RuntimeError setattr(class_n, func_name, a) yield finally: if func_name is not None: # noinspection PyUnboundLocalVariable setattr(class_n, func_name, prev)
def _run_parser(self, class_n, key, name): test_name = {"creator": "can_create", "activators": "supports"} func_name = test_name.get(key) try: if func_name is not None: prev = getattr(class_n, func_name) def a(*args, **kwargs): prev(*args, **kwargs) if key == "activators": return True elif key == "creator": if name == "venv": from virtualenv.create.via_global_ref.venv import Meta return Meta(True, True) from virtualenv.create.via_global_ref.builtin.via_global_self_do import ( Meta, ) return Meta([], True, True) raise RuntimeError setattr(class_n, func_name, a) yield finally: if func_name is not None: # noinspection PyUnboundLocalVariable setattr(class_n, func_name, prev)
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def a(*args, **kwargs): prev(*args, **kwargs) if key == "activators": return True elif key == "creator": if name == "venv": from virtualenv.create.via_global_ref.venv import ViaGlobalRefMeta meta = ViaGlobalRefMeta() meta.symlink_error = None return meta from virtualenv.create.via_global_ref.builtin.via_global_self_do import ( BuiltinViaGlobalRefMeta, ) meta = BuiltinViaGlobalRefMeta() meta.symlink_error = None return meta raise RuntimeError
def a(*args, **kwargs): prev(*args, **kwargs) if key == "activators": return True elif key == "creator": if name == "venv": from virtualenv.create.via_global_ref.venv import Meta return Meta(True, True) from virtualenv.create.via_global_ref.builtin.via_global_self_do import Meta return Meta([], True, True) raise RuntimeError
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def run(args=None, options=None): start = datetime.now() from virtualenv.error import ProcessCallFailed from virtualenv.run import cli_run if args is None: args = sys.argv[1:] try: session = cli_run(args, options) logging.warning(LogSession(session, start)) except ProcessCallFailed as exception: print( "subprocess call failed for {} with code {}".format( exception.cmd, exception.code ) ) print(exception.out, file=sys.stdout, end="") print(exception.err, file=sys.stderr, end="") raise SystemExit(exception.code)
def run(args=None, options=None): start = datetime.now() from virtualenv.error import ProcessCallFailed from virtualenv.run import cli_run if args is None: args = sys.argv[1:] try: session = cli_run(args, options) logging.warning(LogSession(session, start)) except ProcessCallFailed as exception: print("subprocess call failed for {}".format(exception.cmd)) print(exception.out, file=sys.stdout, end="") print(exception.err, file=sys.stderr, end="") raise SystemExit(exception.code)
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def __init__(self, src, must_symlink, must_copy): self.must_symlink = must_symlink self.must_copy = must_copy self.src = src try: self.exists = src.exists() except OSError: self.exists = False self._can_read = None if self.exists else False self._can_copy = None if self.exists else False self._can_symlink = None if self.exists else False if self.must_copy is True and self.must_symlink is True: raise ValueError("can copy and symlink at the same time")
def __init__(self, src, must_symlink, must_copy): self.must_symlink = must_symlink self.must_copy = must_copy self.src = src self.exists = src.exists() self._can_read = None if self.exists else False self._can_copy = None if self.exists else False self._can_symlink = None if self.exists else False if self.must_copy is True and self.must_symlink is True: raise ValueError("can copy and symlink at the same time")
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def run(self, creator, symlinks): bin_dir = self.dest(creator, self.src).parent dest = bin_dir / self.base method = self.method(symlinks) method(self.src, dest) if not symlinks: make_exe(dest) for extra in self.aliases: link_file = bin_dir / extra if link_file.exists(): link_file.unlink() if symlinks: link_file.symlink_to(self.base) else: copy(self.src, link_file) if not symlinks: make_exe(link_file)
def run(self, creator, symlinks): bin_dir = self.dest(creator, self.src).parent dest = bin_dir / self.base method = self.method(symlinks) method(self.src, dest) make_exe(dest) for extra in self.aliases: link_file = bin_dir / extra if link_file.exists(): link_file.unlink() if symlinks: link_file.symlink_to(self.base) else: copy(self.src, link_file) make_exe(link_file)
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def __repr__(self): return "{}(src={}, alias={})".format( self.__class__.__name__, self.src, self.aliases )
def __repr__(self): return "{}(src={})".format(self.__class__.__name__, self.src)
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def can_create(cls, interpreter): """By default all built-in methods assume that if we can describe it we can create it""" # first we must be able to describe it if cls.can_describe(interpreter): meta = cls.setup_meta(interpreter) if meta is not None and meta: for src in cls.sources(interpreter): if src.exists: if meta.can_copy and not src.can_copy: meta.copy_error = "cannot copy {}".format(src) if meta.can_symlink and not src.can_symlink: meta.symlink_error = "cannot symlink {}".format(src) if not meta.can_copy and not meta.can_symlink: meta.error = "neither copy or symlink supported: {}".format( meta.copy_error, meta.symlink_error ) else: meta.error = "missing required file {}".format(src) if meta.error: break meta.sources.append(src) return meta return None
def can_create(cls, interpreter): """By default all built-in methods assume that if we can describe it we can create it""" # first we must be able to describe it if cls.can_describe(interpreter): sources = [] can_copy = True can_symlink = fs_supports_symlink() for src in cls.sources(interpreter): if src.exists: if can_copy and not src.can_copy: can_copy = False logging.debug("%s cannot copy %s", cls.__name__, src) if can_symlink and not src.can_symlink: can_symlink = False logging.debug("%s cannot symlink %s", cls.__name__, src) if not (can_copy or can_symlink): break else: logging.debug("%s missing %s", cls.__name__, src) break sources.append(src) else: return Meta(sources, can_copy, can_symlink) return None
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def can_create(cls, interpreter): if interpreter.has_venv: meta = ViaGlobalRefMeta() if interpreter.platform == "win32" and interpreter.version_info.major == 3: meta = handle_store_python(meta, interpreter) return meta return None
def can_create(cls, interpreter): if interpreter.has_venv: return Meta(can_symlink=fs_supports_symlink(), can_copy=True) return None
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def propose_interpreters(spec, app_data): # 1. if it's a path and exists if spec.path is not None: try: os.lstat( spec.path ) # Windows Store Python does not work with os.path.exists, but does for os.lstat except OSError: if spec.is_abs: raise else: yield PythonInfo.from_exe(os.path.abspath(spec.path), app_data), True if spec.is_abs: return else: # 2. otherwise try with the current yield PythonInfo.current_system(app_data), True # 3. otherwise fallback to platform default logic if IS_WIN: from .windows import propose_interpreters for interpreter in propose_interpreters(spec, app_data): yield interpreter, True # finally just find on path, the path order matters (as the candidates are less easy to control by end user) paths = get_paths() tested_exes = set() for pos, path in enumerate(paths): path = ensure_text(path) logging.debug(LazyPathDump(pos, path)) for candidate, match in possible_specs(spec): found = check_path(candidate, path) if found is not None: exe = os.path.abspath(found) if exe not in tested_exes: tested_exes.add(exe) interpreter = PathPythonInfo.from_exe( exe, app_data, raise_on_error=False ) if interpreter is not None: yield interpreter, match
def propose_interpreters(spec, app_data): # 1. if it's an absolute path and exists, use that if spec.is_abs and os.path.exists(spec.path): yield PythonInfo.from_exe(spec.path, app_data), True # 2. try with the current yield PythonInfo.current_system(app_data), True # 3. otherwise fallback to platform default logic if IS_WIN: from .windows import propose_interpreters for interpreter in propose_interpreters(spec, app_data): yield interpreter, True paths = get_paths() # find on path, the path order matters (as the candidates are less easy to control by end user) tested_exes = set() for pos, path in enumerate(paths): path = ensure_text(path) logging.debug(LazyPathDump(pos, path)) for candidate, match in possible_specs(spec): found = check_path(candidate, path) if found is not None: exe = os.path.abspath(found) if exe not in tested_exes: tested_exes.add(exe) interpreter = PathPythonInfo.from_exe( exe, app_data, raise_on_error=False ) if interpreter is not None: yield interpreter, match
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def _get_via_file_cache(cls, py_info_cache, app_data, resolved_path, exe): key = sha256( str(resolved_path).encode("utf-8") if PY3 else str(resolved_path) ).hexdigest() py_info = None resolved_path_text = ensure_text(str(resolved_path)) try: resolved_path_modified_timestamp = resolved_path.stat().st_mtime except OSError: resolved_path_modified_timestamp = -1 data_file = py_info_cache / "{}.json".format(key) with py_info_cache.lock_for_key(key): data_file_path = data_file.path if ( data_file_path.exists() and resolved_path_modified_timestamp != 1 ): # if exists and matches load try: data = json.loads(data_file_path.read_text()) if ( data["path"] == resolved_path_text and data["st_mtime"] == resolved_path_modified_timestamp ): logging.debug("get PythonInfo from %s for %s", data_file_path, exe) py_info = cls._from_dict({k: v for k, v in data["content"].items()}) else: raise ValueError("force close as stale") except (KeyError, ValueError, OSError): logging.debug("remove PythonInfo %s for %s", data_file_path, exe) data_file_path.unlink() # close out of date files if py_info is None: # if not loaded run and save failure, py_info = _run_subprocess(cls, exe, app_data) if failure is None: file_cache_content = { "st_mtime": resolved_path_modified_timestamp, "path": resolved_path_text, "content": py_info._to_dict(), } logging.debug("write PythonInfo to %s for %s", data_file_path, exe) data_file_path.write_text( ensure_text(json.dumps(file_cache_content, indent=2)) ) else: py_info = failure return py_info
def _get_via_file_cache(cls, py_info_cache, app_data, resolved_path, exe): key = sha256( str(resolved_path).encode("utf-8") if PY3 else str(resolved_path) ).hexdigest() py_info = None resolved_path_text = ensure_text(str(resolved_path)) resolved_path_modified_timestamp = resolved_path.stat().st_mtime data_file = py_info_cache / "{}.json".format(key) with py_info_cache.lock_for_key(key): data_file_path = data_file.path if data_file_path.exists(): # if exists and matches load try: data = json.loads(data_file_path.read_text()) if ( data["path"] == resolved_path_text and data["st_mtime"] == resolved_path_modified_timestamp ): logging.debug("get PythonInfo from %s for %s", data_file_path, exe) py_info = cls._from_dict({k: v for k, v in data["content"].items()}) else: raise ValueError("force close as stale") except (KeyError, ValueError, OSError): logging.debug("remove PythonInfo %s for %s", data_file_path, exe) data_file_path.unlink() # close out of date files if py_info is None: # if not loaded run and save failure, py_info = _run_subprocess(cls, exe, app_data) if failure is None: file_cache_content = { "st_mtime": resolved_path_modified_timestamp, "path": resolved_path_text, "content": py_info._to_dict(), } logging.debug("write PythonInfo to %s for %s", data_file_path, exe) data_file_path.write_text( ensure_text(json.dumps(file_cache_content, indent=2)) ) else: py_info = failure return py_info
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def _find_possible_folders(self, inside_folder): candidate_folder = OrderedDict() executables = OrderedDict() executables[os.path.realpath(self.executable)] = None executables[self.executable] = None executables[os.path.realpath(self.original_executable)] = None executables[self.original_executable] = None for exe in executables.keys(): base = os.path.dirname(exe) # following path pattern of the current if base.startswith(self.prefix): relative = base[len(self.prefix) :] candidate_folder["{}{}".format(inside_folder, relative)] = None # or at root level candidate_folder[inside_folder] = None return list(i for i in candidate_folder.keys() if os.path.exists(i))
def _find_possible_folders(self, inside_folder): candidate_folder = OrderedDict() executables = OrderedDict() executables[os.path.realpath(self.executable)] = None executables[self.executable] = None executables[os.path.realpath(self.original_executable)] = None executables[self.original_executable] = None for exe in executables.keys(): base = os.path.dirname(exe) # following path pattern of the current if base.startswith(self.prefix): relative = base[len(self.prefix) :] candidate_folder["{}{}".format(inside_folder, relative)] = None # or at root level candidate_folder[inside_folder] = None return list(candidate_folder.keys())
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def from_string_spec(cls, string_spec): impl, major, minor, micro, arch, path = None, None, None, None, None, None if os.path.isabs(string_spec): path = string_spec else: ok = False match = re.match(PATTERN, string_spec) if match: def _int_or_none(val): return None if val is None else int(val) try: groups = match.groupdict() version = groups["version"] if version is not None: versions = tuple(int(i) for i in version.split(".") if i) if len(versions) > 3: raise ValueError if len(versions) == 3: major, minor, micro = versions elif len(versions) == 2: major, minor = versions elif len(versions) == 1: version_data = versions[0] major = int(str(version_data)[0]) # first digit major if version_data > 9: minor = int(str(version_data)[1:]) ok = True except ValueError: pass else: impl = groups["impl"] if impl == "py" or impl == "python": impl = "CPython" arch = _int_or_none(groups["arch"]) if not ok: path = string_spec return cls(string_spec, impl, major, minor, micro, arch, path)
def from_string_spec(cls, string_spec): impl, major, minor, micro, arch, path = None, None, None, None, None, None if os.path.isabs(string_spec): path = string_spec else: ok = False match = re.match(PATTERN, string_spec) if match: def _int_or_none(val): return None if val is None else int(val) try: groups = match.groupdict() version = groups["version"] if version is not None: versions = tuple(int(i) for i in version.split(".") if i) if len(versions) > 3: raise ValueError if len(versions) == 3: major, minor, micro = versions elif len(versions) == 2: major, minor = versions elif len(versions) == 1: version_data = versions[0] major = int(str(version_data)[0]) # first digit major if version_data > 9: minor = int(str(version_data)[1:]) ok = True except ValueError: pass else: impl = groups["impl"] if impl == "py" or impl == "python": impl = "CPython" arch = _int_or_none(groups["arch"]) if not ok: path = os.path.abspath(string_spec) return cls(string_spec, impl, major, minor, micro, arch, path)
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def generate_names(self): if self.implementation is None: return impls = OrderedDict() if self.implementation: # first consider implementation as it is impls[self.implementation] = False if fs_is_case_sensitive(): # for case sensitive file systems consider lower and upper case versions too # trivia: MacBooks and all pre 2018 Windows-es were case insensitive by default impls[self.implementation.lower()] = False impls[self.implementation.upper()] = False impls["python"] = ( True # finally consider python as alias, implementation must match now ) version = self.major, self.minor, self.micro try: version = version[: version.index(None)] except ValueError: pass for impl, match in impls.items(): for at in range(len(version), -1, -1): cur_ver = version[0:at] spec = "{}{}".format(impl, ".".join(str(i) for i in cur_ver)) yield spec, match
def generate_names(self): impls = OrderedDict() if self.implementation: # first consider implementation as it is impls[self.implementation] = False if fs_is_case_sensitive(): # for case sensitive file systems consider lower and upper case versions too # trivia: MacBooks and all pre 2018 Windows-es were case insensitive by default impls[self.implementation.lower()] = False impls[self.implementation.upper()] = False impls["python"] = ( True # finally consider python as alias, implementation must match now ) version = self.major, self.minor, self.micro try: version = version[: version.index(None)] except ValueError: pass for impl, match in impls.items(): for at in range(len(version), -1, -1): cur_ver = version[0:at] spec = "{}{}".format(impl, ".".join(str(i) for i in cur_ver)) yield spec, match
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def __init__(self, interpreter, parser): creators, self.key_to_meta, self.describe, self.builtin_key = self.for_interpreter( interpreter ) super(CreatorSelector, self).__init__(interpreter, parser, "creator", creators)
def __init__(self, interpreter, parser): creators, self.key_to_meta, self.describe, self.builtin_key = self.for_interpreter( interpreter ) if not creators: raise RuntimeError("No virtualenv implementation for {}".format(interpreter)) super(CreatorSelector, self).__init__(interpreter, parser, "creator", creators)
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def for_interpreter(cls, interpreter): key_to_class, key_to_meta, builtin_key, describe = OrderedDict(), {}, None, None errored = defaultdict(list) for key, creator_class in cls.options("virtualenv.create").items(): if key == "builtin": raise RuntimeError("builtin creator is a reserved name") meta = creator_class.can_create(interpreter) if meta: if meta.error: errored[meta.error].append(creator_class) else: if "builtin" not in key_to_class and issubclass( creator_class, VirtualenvBuiltin ): builtin_key = key key_to_class["builtin"] = creator_class key_to_meta["builtin"] = meta key_to_class[key] = creator_class key_to_meta[key] = meta if ( describe is None and issubclass(creator_class, Describe) and creator_class.can_describe(interpreter) ): describe = creator_class if not key_to_meta: if errored: raise RuntimeError( "\n".join( "{} for creators {}".format(k, ", ".join(i.__name__ for i in v)) for k, v in errored.items() ) ) else: raise RuntimeError( "No virtualenv implementation for {}".format(interpreter) ) return CreatorInfo( key_to_class=key_to_class, key_to_meta=key_to_meta, describe=describe, builtin_key=builtin_key, )
def for_interpreter(cls, interpreter): key_to_class, key_to_meta, builtin_key, describe = OrderedDict(), {}, None, None for key, creator_class in cls.options("virtualenv.create").items(): if key == "builtin": raise RuntimeError("builtin creator is a reserved name") meta = creator_class.can_create(interpreter) if meta: if "builtin" not in key_to_class and issubclass( creator_class, VirtualenvBuiltin ): builtin_key = key key_to_class["builtin"] = creator_class key_to_meta["builtin"] = meta key_to_class[key] = creator_class key_to_meta[key] = meta if ( describe is None and issubclass(creator_class, Describe) and creator_class.can_describe(interpreter) ): describe = creator_class return CreatorInfo( key_to_class=key_to_class, key_to_meta=key_to_meta, describe=describe, builtin_key=builtin_key, )
https://github.com/pypa/virtualenv/issues/1709
(venv) C:\Users\IEUser\astpretty>virtualenv v -vvv --with-traceback 390 setup logging to NOTSET [DEBUG report:43] 468 could not create app data folder C:\Users\IEUser\AppData\Local\pypa\virtualenv due to FileNotFoundError(2, 'The system cannot find the path specified') [INFO app_data:54] 577 created temporary app data folder C:\Users\IEUser\AppData\Local\Temp\tmpaqvhomd3 [DEBUG app_data:32] 624 find interpreter for spec PythonSpec(path=c:\users\ieuser\astpretty\venv\scripts\python.exe) [INFO builtin:44] Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\IEUser\astpretty\venv\Scripts\virtualenv.exe\__main__.py", line 9, in <module> File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 50, in run_with_catch run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\__main__.py", line 20, in run session = cli_run(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 27, in cli_run session = session_via_cli(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 35, in session_via_cli parser = build_parser(args, options) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\run\__init__.py", line 71, in build_parser parser._interpreter = interpreter = discover.interpreter File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\discover.py", line 44, in interpreter self._interpreter = self.run() File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 33, in run return get_interpreter(self.python_spec, self.app_data.folder) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 46, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec, app_data): File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\builtin.py", line 60, in propose_interpreters yield PythonInfo.from_exe(spec.path, app_data), True File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(app_data, proposed) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 328, in _resolve_to_system target = cls.from_exe(target.system_executable, app_data) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\py_info.py", line 290, in from_exe proposed = from_exe(cls, app_data, exe, raise_on_error=raise_on_error, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 32, in from_exe result = _get_from_cache(cls, py_info_cache, app_data, exe, ignore_cache=ignore_cache) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 56, in _get_from_cache py_info = _get_via_file_cache(cls, py_info_cache, app_data, exe_path, exe) File "c:\users\ieuser\astpretty\venv\lib\site-packages\virtualenv\discovery\cached_py_info.py", line 68, in _get_via_file_cache resolved_path_modified_timestamp = resolved_path.stat().st_mtime File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\pathlib.py", line 1178, in stat return self._accessor.stat(self) OSError: [WinError 1920] The file cannot be accessed by the system: 'C:\\Users\\IEUser\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\\python.exe'
OSError
def find_spec(self, fullname, path, target=None): if fullname in _DISTUTILS_PATCH and self.fullname is None: with self.lock: self.fullname = fullname try: spec = find_spec(fullname, path) if spec is not None: # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work spec.loader = deepcopy( spec.loader ) # loaders may be shared, create new that also patches func_name = ( "exec_module" if hasattr(spec.loader, "exec_module") else "load_module" ) if func_name == "exec_module": # new API def patch_module_load(module): old(module) patch_dist(module) else: # legacy API def patch_module_load(name): module = old(name) patch_dist(module) return module old = getattr(spec.loader, func_name) setattr(spec.loader, func_name, patch_module_load) return spec finally: self.fullname = None
def find_spec(self, fullname, path, target=None): if fullname in _DISTUTILS_PATCH and self.fullname is None: with self.lock: self.fullname = fullname try: spec = find_spec(fullname, path) if spec is not None: old = spec.loader.exec_module def exec_module(module): old(module) patch_dist(module) spec.loader.exec_module = exec_module return spec finally: self.fullname = None
https://github.com/pypa/virtualenv/issues/1690
Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 888, in _find_spec AttributeError: 'PymonkeyImportHook' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/pymonkey/testing/pkg1/patchingmod_main.py", line 8, in <module> exit(main()) File "/tmp/pymonkey/pymonkey.py", line 270, in entry tuple(patches) + ('--', original_entry_point) + tuple(argv) File "/tmp/pymonkey/pymonkey.py", line 258, in main return entry.load()() File "/tmp/pymonkey/.tox/py36/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2445, in load return self.resolve() File "/tmp/pymonkey/.tox/py36/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2451, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 656, in _load_unlocked File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible File "/tmp/pymonkey/pymonkey.py", line 173, in load_module module = importmod(fullname) File "/tmp/pymonkey/pymonkey.py", line 94, in importmod return __import__(mod, fromlist=[str('__name__')], level=0) File "/tmp/pymonkey/testing/pkg2/targetmod.py", line 4, in <module> import setuptools # Some weird import hook File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 656, in _load_unlocked File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible File "/tmp/pymonkey/pymonkey.py", line 173, in load_module module = importmod(fullname) File "/tmp/pymonkey/pymonkey.py", line 94, in importmod return __import__(mod, fromlist=[str('__name__')], level=0) File "/tmp/pymonkey/.tox/py36/lib/python3.6/site-packages/setuptools/__init__.py", line 5, in <module> import distutils.core File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 656, in _load_unlocked File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible File "/tmp/pymonkey/pymonkey.py", line 173, in load_module module = importmod(fullname) File "/tmp/pymonkey/pymonkey.py", line 94, in importmod return __import__(mod, fromlist=[str('__name__')], level=0) File "/usr/lib/python3.6/distutils/core.py", line 16, in <module> from distutils.dist import Distribution File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 951, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 890, in _find_spec File "<frozen importlib._bootstrap>", line 864, in _find_spec_legacy File "/tmp/pymonkey/pymonkey.py", line 162, in find_module elif self._module_exists(fullname, path): File "/tmp/pymonkey/pymonkey.py", line 122, in _module_exists getattr(entry, 'find_spec', _noop)(module, path) or File "/tmp/pymonkey/.tox/py36/lib/python3.6/site-packages/_virtualenv.py", line 58, in find_spec old = spec.loader.exec_module AttributeError: 'PymonkeyImportHook' object has no attribute 'exec_module'
AttributeError
def _resolve_to_system(cls, target): start_executable = target.executable prefixes = OrderedDict() while target.system_executable is None: prefix = target.real_prefix or target.base_prefix or target.prefix if prefix in prefixes: if len(prefixes) == 1: # if we're linking back to ourselves accept ourselves with a WARNING logging.info("%r links back to itself via prefixes", target) target.system_executable = target.executable break for at, (p, t) in enumerate(prefixes.items(), start=1): logging.error("%d: prefix=%s, info=%r", at, p, t) logging.error("%d: prefix=%s, info=%r", len(prefixes) + 1, prefix, target) raise RuntimeError( "prefixes are causing a circle {}".format("|".join(prefixes.keys())) ) prefixes[prefix] = target target = target.discover_exe(prefix=prefix, exact=False) if target.executable != target.system_executable: target = cls.from_exe(target.system_executable) target.executable = start_executable return target
def _resolve_to_system(cls, target): start_executable = target.executable prefixes = OrderedDict() while target.system_executable is None: prefix = target.real_prefix or target.base_prefix or target.prefix if prefix in prefixes: for at, (p, t) in enumerate(prefixes.items(), start=1): logging.error("%d: prefix=%s, info=%r", at, p, t) logging.error("%d: prefix=%s, info=%r", len(prefixes) + 1, prefix, target) raise RuntimeError( "prefixes are causing a circle {}".format("|".join(prefixes.keys())) ) prefixes[prefix] = target target = target.discover_exe(prefix=prefix, exact=False) if target.executable != target.system_executable: target = cls.from_exe(target.system_executable) target.executable = start_executable return target
https://github.com/pypa/virtualenv/issues/1632
66 setup logging to NOTSET [DEBUG report:43] 74 find interpreter for spec PythonSpec(path=/Users/carson.gee/.virtualenvs/test-pytest/bin/python3.7) [INFO builtin:43] 74 discover system for PythonInfo(spec=CPython3.7.6.final.0-64, exe=/Users/carson.gee/.virtualenvs/test-pytest/bin/python3.7, platform=darwin, version='3.7.6 (default, Dec 30 2019, 17:49:05) \n[Clang 10.0.1 (clang-1001.0.46.4)]', encoding_fs_io=utf-8-UTF-8) in /Users/carson.gee/.virtualenvs/test-pytest [DEBUG py_info:335] 76 filesystem is not case-sensitive [DEBUG info:28] 76 1: prefix=/Users/carson.gee/.virtualenvs/test-pytest, info=PythonInfo({'platform': 'darwin', 'implementation': 'CPython', 'version_info': VersionInfo(major=3, minor=7, micro=6, releaselevel='final', serial=0), 'architecture': 64, 'version': '3.7.6 (default, Dec 30 2019, 17:49:05) \n[Clang 10.0.1 (clang-1001.0.46.4)]', 'os': 'posix', 'prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'base_prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'real_prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'base_exec_prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'exec_prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'executable': '/Users/carson.gee/.virtualenvs/test-pytest/bin/python3.7', 'original_executable': '/Users/carson.gee/.virtualenvs/test-pytest/bin/python3.7', 'system_executable': None, 'has_venv': True, 'path': ['/Users/carson.gee/tmp/pytest-stereo', '/Users/carson.gee/.virtualenvs/test-pytest/lib/python37.zip', '/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7', '/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/lib-dynload', '/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages'], 'file_system_encoding': 'utf-8', 'stdout_encoding': 'UTF-8', 'sysconfig_paths': {'stdlib': '{installed_base}/lib/python{py_version_short}', 'platstdlib': '{platbase}/lib/python{py_version_short}', 'purelib': '{base}/lib/python{py_version_short}/site-packages', 'platlib': '{platbase}/lib/python{py_version_short}/site-packages', 'include': '{installed_base}/include/python{py_version_short}{abiflags}', 'scripts': '{base}/bin', 'data': '{base}'}, 'sysconfig_vars': {'abiflags': 'm', 'base': '/Users/carson.gee/.virtualenvs/test-pytest', 'platbase': '/Users/carson.gee/.virtualenvs/test-pytest', 'py_version_short': '3.7', 'installed_base': '/Users/carson.gee/.virtualenvs/test-pytest'}, 'distutils_install': {'purelib': 'lib/python3.7/site-packages', 'platlib': 'lib/python3.7/site-packages', 'headers': 'include/python3.7m/UNKNOWN', 'scripts': 'bin', 'data': ''}, 'system_stdlib': '/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7'}) [ERROR py_info:317] 77 2: prefix=/Users/carson.gee/.virtualenvs/test-pytest, info=PythonInfo({'platform': 'darwin', 'implementation': 'CPython', 'version_info': VersionInfo(major=3, minor=7, micro=6, releaselevel='final', serial=0), 'architecture': 64, 'version': '3.7.6 (default, Dec 30 2019, 17:49:05) \n[Clang 10.0.1 (clang-1001.0.46.4)]', 'os': 'posix', 'prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'base_prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'real_prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'base_exec_prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'exec_prefix': '/Users/carson.gee/.virtualenvs/test-pytest', 'executable': '/Users/carson.gee/.virtualenvs/test-pytest/bin/python3.7', 'original_executable': '/Users/carson.gee/.virtualenvs/test-pytest/bin/python3.7', 'system_executable': None, 'has_venv': True, 'path': ['/Users/carson.gee/tmp/pytest-stereo', '/Users/carson.gee/.virtualenvs/test-pytest/lib/python37.zip', '/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7', '/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/lib-dynload', '/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages'], 'file_system_encoding': 'utf-8', 'stdout_encoding': 'UTF-8', 'sysconfig_paths': {'stdlib': '{installed_base}/lib/python{py_version_short}', 'platstdlib': '{platbase}/lib/python{py_version_short}', 'purelib': '{base}/lib/python{py_version_short}/site-packages', 'platlib': '{platbase}/lib/python{py_version_short}/site-packages', 'include': '{installed_base}/include/python{py_version_short}{abiflags}', 'scripts': '{base}/bin', 'data': '{base}'}, 'sysconfig_vars': {'abiflags': 'm', 'base': '/Users/carson.gee/.virtualenvs/test-pytest', 'platbase': '/Users/carson.gee/.virtualenvs/test-pytest', 'py_version_short': '3.7', 'installed_base': '/Users/carson.gee/.virtualenvs/test-pytest'}, 'distutils_install': {'purelib': 'lib/python3.7/site-packages', 'platlib': 'lib/python3.7/site-packages', 'headers': 'include/python3.7m/UNKNOWN', 'scripts': 'bin', 'data': ''}, 'system_stdlib': '/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7'}) [ERROR py_info:318] Traceback (most recent call last): File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/__main__.py", line 47, in <module> run_with_catch() File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/__main__.py", line 36, in run_with_catch run(args, options) File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/__main__.py", line 19, in run session = cli_run(args, options) File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/run/__init__.py", line 22, in cli_run session = session_via_cli(args, options) File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/run/__init__.py", line 29, in session_via_cli parser = build_parser(args, options) File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/run/__init__.py", line 49, in build_parser parser._interpreter = interpreter = discover.interpreter File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/discovery/discover.py", line 44, in interpreter self._interpreter = self.run() File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/discovery/builtin.py", line 32, in run return get_interpreter(self.python_spec) File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/discovery/builtin.py", line 45, in get_interpreter for interpreter, impl_must_match in propose_interpreters(spec): File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/discovery/builtin.py", line 59, in propose_interpreters yield PythonInfo.from_exe(spec.path), True File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/discovery/py_info.py", line 293, in from_exe proposed = proposed._resolve_to_system(proposed) File "/Users/carson.gee/.virtualenvs/test-pytest/lib/python3.7/site-packages/virtualenv/discovery/py_info.py", line 319, in _resolve_to_system raise RuntimeError("prefixes are causing a circle {}".format("|".join(prefixes.keys()))) RuntimeError: prefixes are causing a circle /Users/carson.gee/.virtualenvs/test-pytest
RuntimeError
def create(self): dirs = self.ensure_directories() for directory in list(dirs): if any( i for i in dirs if i is not directory and directory.parts == i.parts[: len(directory.parts)] ): dirs.remove(directory) for directory in sorted(dirs): ensure_dir(directory) self.set_pyenv_cfg() self.pyenv_cfg.write() true_system_site = self.enable_system_site_package try: self.enable_system_site_package = False for src in self._sources: src.run(self, self.symlinks) finally: if true_system_site != self.enable_system_site_package: self.enable_system_site_package = true_system_site super(ViaGlobalRefVirtualenvBuiltin, self).create()
def create(self): dirs = self.ensure_directories() for directory in list(dirs): if any( i for i in dirs if i is not directory and directory.parts == i.parts[: len(directory.parts)] ): dirs.remove(directory) for directory in sorted(dirs): ensure_dir(directory) self.set_pyenv_cfg() self.pyenv_cfg.write() true_system_site = self.enable_system_site_package try: self.enable_system_site_package = False for src in self._sources: src.run(self, self.symlinks) finally: if true_system_site != self.enable_system_site_package: self.enable_system_site_package = true_system_site
https://github.com/pypa/virtualenv/issues/1635
~ % source venv/bin/activate source: no such file or directory: venv/bin/activate ~ % source venv/usr/local/opt/python@3.6.8/bin/activate (venv) ~ % pip list Traceback (most recent call last): File "/Users/csalch/venv/usr/local/opt/python@3.6.8/bin/pip", line 5, in <module> from pip._internal.cli.main import main ModuleNotFoundError: No module named 'pip._internal.cli.main' (venv) ~ % which python /Users/csalch/venv/usr/local/opt/python@3.6.8/bin/python (venv) ~ % python -m pip list Package Version ------------------- ------- anisble 0.1 ansible 2.9.4 appdirs 1.4.3 cffi 1.13.2 cryptography 2.8 distlib 0.3.0 filelock 3.0.12 importlib-metadata 1.5.0 importlib-resources 1.0.2 Jinja2 2.10.3 MarkupSafe 1.1.1 pip 19.3.1 pycparser 2.19 PyYAML 5.3 ruamel.yaml 0.16.5 ruamel.yaml.clib 0.2.0 setuptools 42.0.2 six 1.13.0 virtualenv 20.0.4 wheel 0.33.6 zipp 2.2.0 (venv) ~ % cat $(which pip) #!/Users/csalch/venv/usr/local/opt/python@3.6.8/bin/python # -*- coding: utf-8 -*- import re import sys from pip._internal.cli.main import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main()) (venv) ~ %
ModuleNotFoundError