Reputation: 83
I am trying to run code which can find installed packages within my Python environment and install those which are not found within requirements.txt
. I keep getting an error on the line:
required = {requirements}
Here is my code so far:
with open ('requirements.txt', "r") as myfile:
requirements = myfile.read().splitlines()
#requirements=myfile.readlines()
#requirements=myfile.read().replace('\n', '')
print(requirements)
#file_read('test.txt')
required = {requirements}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
python = sys.executable
subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)
else:
print("prerequisites found")
I keep getting the 'Unhashable' error which I know has something to do with the extracted list but I am not sure how to tackle the problem.
Thanks in advance.
Upvotes: 0
Views: 155
Reputation: 77347
The problem is that you are trying to add the single list object to the set. Lists are mutable and not hashable, so it fails. Instead, you want to put the values of the list into the set. Either set(requirements)
, {*requirements}
or {line for line in requirements}
will do.
>>> requirements = "foo\nbar\nbaz".splitlines()
>>> requirements
['foo', 'bar', 'baz']
>>> {requirements}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> set(requirements)
{'foo', 'bar', 'baz'}
Upvotes: 1