I have a python module with lots of python scripts in, I want to read these scripts and check if a variable is set.
I'm currently reading the files line by line, but as the scripts i'm reading are in python i'm guessing there is a better way?
for filename in glob.glob(os.path.join(my_path, '*.py')):
with open(filename) as f:
for line in f:
if 'my_variable' in line:
variable_exists = True
Edit
I have a directory which has lots of classes, some have variables which affect how the script runs. e.g.
class Script1():
name = 'script1'
countrys = ['US', 'UK', 'AU']
class Script2():
name = 'script2'
countrys = ['US', 'CA']
From this i want to achieve
[
{'name': 'script1', 'country': 'US'},
{'name': 'script1', 'country': 'UK'},
{'name': 'script1', 'country': 'AU'},
{'name': 'script2', 'country': 'US'},
{'name': 'script2', 'country': 'CA'}
]
Here's a working example for your question:
import glob
import inspect
import os
import sys
import importlib
def get_classes(module):
def pred(c):
if inspect.isclass(c) and hasattr(c, "countrys"):
return True
return False
for value in inspect.getmembers(module, pred):
yield value
def list_plugins(search_paths, my_path):
output = set()
for path in search_paths:
sys_path = list(sys.path)
sys.path.insert(0, path)
for f in glob.glob(my_path):
print f
location, ext = os.path.splitext(f)
mod_name = os.path.basename(location)
mod = importlib.import_module(mod_name)
print os.path.abspath(mod.__file__)
for c in get_classes(mod):
output.add(c)
sys.path[:] = sys_path
return output
if __name__ == "__main__":
output = []
for p in list_plugins(["test"], os.path.join("test","*.py")):
name, plugin = p[0], p[1]
for c in plugin.countrys:
output.append({
'name': name,
'country': c
})
print output
Some comments, to make it work, create a folder in the same script's folder called test containing an empty __init__.py file and one (or more) python files with the classes you've mentioned in your question.
The important bits of the code are the usage of import_module and inspect
It's a little example but it should be a good starting point for you. Hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With