Importing Dictionary Fails - python

I'm trying to get too clever for my own good and have split out the data in my python script into three files. I want to bring the two reference files dictionaries into the main script, but can't get them to load no matter what I do. I'm sure its something simple, but I'm at my wits end. All the files are in the same folder.
Swordguy.py
stats = {
"Name":"Swordguy",
"Hp":20,
"Mp":20,
"St":20,
"Fight":8,
"Magic":2,
"Sneak":4,
"Athletics":2,
"Animal":0,
"Traps":-2
}
Room.py
info = {
"Name": "Rat Warren",
"Fight": 0,
"Magic": 2,
"Sneak": -2,
"Athletics": 0,
"Animal": 2
}
Testing.py
from Swordguy import stats
from Room import info
charname = stats["Name"]
roomname = info["Name"]
print(stats["Name"]+" arrives in the room "+info["Name"])
End result should read Swordguy arrived in the room Rat Warren but I'm getting the error message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'stats' from 'Swordguy'
I'm running the code in Visual Studio Core. I'm just using the inbuilt run command shift+enter
Edit 2: Looks like something is going on in how I'm running the code. Thanks everyone, glad its not just me losing my marbles.

You can make a function in Swordguy.py like this
def get_stats():
return stats
And do the same for Room.py
Now in testing.py import that function and call it like
from Swordguy import get_stats
from Room import get_info
stats = get_stats()
info = get_info()
charname = stats["Name"]
roomname = info["Name"]

Related

ImportError "text_process" Python library

I'm taking a look at some CBOW Python implementations.
The owner of the code used a function called "line_processing" from text_process lib.
When I tried to run, I got that error:
ImportError: cannot import name 'line_processing' from 'text_process'
So I took a look at the lib implementation. There is no function called "line_processing".
That guy used this function to read each line from a .txt file, and write them in a variable, creating a "big string":
text = 'file.txt'
print(text)
text = ''
count = 0
for i in open(text_file, 'r', encoding='utf-8'):
text+=line_processing(i)+'\n'
count += 1
if count % 10000 == 0: break
Is there anyone who knows something about "line_processing" function, or about a function/lib I can use instead?
Thank you!
Ps.:
$ python CBOW.py
Building prefix dict from the default dictionary ...
Dumping model to file cache C:\"path_to"\AppData\Local\Temp\jieba.cache
Loading model cost 0.723 seconds.
Prefix dict has been built successfully.
Traceback (most recent call last):
File "CBOW.py", line 1, in <module>
from text_process import line_processing
ImportError: cannot import name 'line_processing' from 'text_process' (C:\"path_to"\miniconda3\lib\site\...\text_process)

Using string variable within Dict type variable

We have 3 different Datacenter environments, for reference, let us say, US, CA and IN. All three have a puppetdb master different to the other 2. So while automating some stuff, I want to a config.json file like below and reference it from the main code based on the parameters passed:
// config.json
{
"DEFAULT": {
"LOGFILE": "log/get_hname.log",
"LOCKDIR": "include/LOCK",
"NOOPRUN": "0"
},
"US": {
"PDB": "puppetdb100.us",
"VRFFILE": "include/vrf.txt",
"FQDN": "us.livevox"
},
"CA": {
"PDB": "puppet.ca.livevox.net",
"FQDN": "ca.livevox"
},
"IN": {
"PDB": "puppet100.in.livevox.net",
"FQDN": "in.livevox"
}
}
Now, for the main script, where I am trying to use a variable called "myenv", which would be one of US, or CA or IN to refer the key in the config which is of dict type. But I keep getting the error as below:
Traceback (most recent call last):
File "./get_hname.py", line 94, in <module>
print (config[myenv.upper()]['PDB'])
KeyError: 'NONE'
The script itself for your reference below:
#!/usr/bin/env python
import argparse
import json
import sys
import os
import logging
import time
from argparse import ArgumentParser
# Where Config File lives --------
CONFFILE = "include/get-hname-cfg.json"
# - DO NOT EDIT BELOW THIS LINE --
with open(CONFFILE, 'r') as f:
config = json.load(f)
logfile = config['DEFAULT']['LOGFILE']
myarguments = argparse.ArgumentParser(description="Arguments for Name Builder", usage="%(prog)s [options]")
myarguments.add_argument("-e", "--env", type=str, metavar="environment", nargs='*', help="Environment")
myarguments.add_argument("-t", "--type", type=str, metavar="servertype", nargs='*', help="Server type")
myarguments.add_argument("-n", "--noop", action="store_true", help="Stimulate the whole run, but don't execute. Similar to noop")
myarguments.parse_args()
args = myarguments.parse_args()
if not args.env and not args.type:
myarguments.print_help(sys.stderr)
myenv = str(args.env).lower()
pdbhost = "config" +myenv.upper()+ "['PDB']"
print ("%s" %(pdbhost))
if config[myenv.upper()]['PDB'] in globals():
puppetdbhost = config[myenv.upper()]['PDB']
How can I use the string type variable within a dict as a key?
EDIT : Please note, all necessary indentations which maybe missing in my question, have all been taken care of, since I'm using PyCharm.
Traceback (most recent call last):
File "./get_hname.py", line 94, in <module>
print (config[myenv.upper()]['PDB'])
KeyError: 'NONE'
It's mean that myenv variable is string 'None' in that moment. Check it.
you need to modify your add_arguments remove nargs='*' which is giving env in list
form see below example:
myarguments.add_argument("-e", "--env", type=str, metavar="environment", help="Environment")
refer this document for more info.
OK folks, I found what I was doing wrong. The arguments I was using
type=str and nargs='*'
which is why I was facing a type mismatch and getting the output as ['US'] instead of US (or CA or IN). Once I removed that, things are working fine.
Thank you all for your pointers. That helped.

Python in ArcGIS

I wrote the following code, which results in an error and I don't know how to fix it to work.
The code is:
# Name: ClipGDBtoNewGDB.py
# Description: Take an input GDB, create a list, iterate through each
feature class, clipping it and writing it to a new GDB.
# Author: tuilbox
# Import system modules
import arcpy, os
from arcpy import env
# Set workspace
env.workspace = arcpy.GetParameterAsText(0)
arcpy.env.overwriteOutput=True
# Set local variables
fclist = arcpy.ListFeatureClasses()
clip_features = arcpy.GetParameterAsText(1)
output_directory=arcpy.GetParameterAsText(2)
xy_tolerance = ""
outgdb=os.path.join(output_directory, arcpy.GetParameterAsText(3))
if not arcpy.Exists(outgdb):
arcpy.CreateFileGDB_management(output_directory,
arcpy.GetParameterAsText(3))
# Execute Clip within for loop
for fc in fclist:
arcpy.Clip_analysis(fc, clip_features, os.path.join(outgdb, fc))
The error is: Traceback (most recent call last):
File "F:/GIS_Joseph/Lab10_Joseph/ClipGDBtoNewGDB.py", line 17, in <module>
arcpy.CreateFileGDB_management(output_directory, arcpy.GetParameterAsText(3))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 18878, in CreateFileGDB
raise e
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000735: File GDB Location: Value is required
ERROR 000735: File GDB Name: Value is required
Failed to execute (CreateFileGDB).
Any help would be appreciated. Thank you.
With this type of question it would be helpful to let us know what parameters you are passing into your script. Have you passed a valid parameter in position 3? Use arcpy.AddMessage to double check what value you are attempting to pass to arcpy.CreateFileGDB_management.

How to get all inventory groups variables in hierarchy via Python API?

I want to collect all inventory hosts groups variables in hierarchy data struct and send them to Consul to make them available in runtime.
Calling this method - https://github.com/ansible/ansible/blob/devel/lib/ansible/inventory/manager.py#L160 I got the error
inventory.get_vars()
Traceback (most recent call last):
File "<input>", line 1, in <module>
inventory.get_vars()
File "<>/.virtualenvs/ansible27/lib/python2.7/site-packages/ansible/inventory/manager.py", line 160, in get_vars
return self._inventory.get_vars(args, kwargs)
AttributeError: 'InventoryData' object has no attribute 'get_vars'
my script
import pprint
pp = pprint.PrettyPrinter(indent=4).pprint
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
loader = DataLoader()
inventory = InventoryManager(loader=loader, sources='inventories/itops-vms.yml')
variable_manager = VariableManager(loader=loader, inventory=inventory)
# shows groups as well
pp(inventory.groups)
# shows dict as well with content
pp(variable_manager.get_vars())
# creates an unhandled exception
inventory.get_vars()
How to do that right way?
Python 2.7.15
ansible==2.6.2
OS Mac High Siera
The error itself seems to be caused by a bug - the get_vars method of the inventory object calls get_vars method of the InventoryData object which is not implemented.
You need to specify the group, for example:
>>> inventory.groups['all'].get_vars()
{u'my_var': u'value'}
You can create a dictionary with that data:
{g: inventory.groups[g].get_vars() for g in inventory.groups}
The above gets only the variables defined in the inventory itself (which is what the question asks about). If you wanted to get a structure with variables from group_vars, host_vars, etc. (as you indicated in your comment I want to get something similar to $ ansible-inventory -i inventories/itops-vms.yml --graph --vars you'd need to collect the data from different sources, just like Ansible does.

Calling a function within a function with python

so here is my problem, I am trying to create a function in Python that refers to another function
Here is my code:
def movies_creation():
for director in directors:
for i in range((int(director.age)-20)/random.randint(1,5)):
movie = MOVIE([], random.randint(1960, 2015),
random.choice(movie_genre), 0, [], director, 0, 0, 0)
movie_title_type = random.randint(1,40)
if movie_title_type == 1:
title_colors()
director.filmography.append(movie)
def title_colors():
movie.name.append(random.choice(title_colors))
Now when I try to run this code I get this error message:
Traceback (most recent call last):
File "C:\Users\Patrick\Pictures\Python\TS\gui.py", line 7, in
movies_creation()
File "C:\Users\Patrick\Pictures\Python\TS\Movies.py", line 401, in movies_creation
title_colors()
File "C:\Users\Patrick\Pictures\Python\TS\Movies.py", line 343, in title_colors
movie.name.append(random.choice(title_colors)) NameError: global name 'movie' is not defined
Not sure what I am doing wrong...
Problem in your code is that you should pass the movie variable to the method title_colors:
title_colors(movie)
def title_colors(m):
m.name.append(random.choice(title_colors))
Thanks for your help, my problem was my function had the same name than a list in my program. changed the name and everything works fine now

Categories

Resources