Importing packages in Python3 - python-3.4

How do I import packages in Python3?
-Package1
|
--InnerPackage1
||
| ---InnerInnerPackage1
| ---InnerInnerPackage2
| ---InnerInnerPackage3
--InnerPackage2
||---InnerInnerPackage4
||---InnerInnerPackage5
||---InnerInnerPackage6
||---InnerInnerPackage7
--InnerPackage3
||---InnerInnerPackage8
||---InnerInnerPackage9
|||
|| ----InnerInnerInnerPackage10
|| ----InnerInnerInnerPackage11
||---InnerInnerPackage12
|||----InnerInnerInnerPackage12
|||----InnerInnerInnerPackage13
|||----InnerInnerInnerPackage14
||---InnerInnerPackge13
Now, let my directory structure be similar to what I've mentioned above, how do I import a package, when my current directory is suppose InnerInnerInnerPackage12, and I have to import InnerInnerPackage6.
Though, when I import, while traversing above using this syntax,
from InnerPackage2 import InnerInnerPackage6
Else, one can also imply importing from the root package
Package1.InnerPackage2.InnerInnerPackage6
Another logic says,
import sys.path
sys.path.insert(0, '%package_directory%\\Package1\\InnerPackage2\\InnerInnerPackage6')
That works in cmd.
Still what would be the correct way to import a module.
It gives an error on running the code in CMD, but when I run the code in JetBrains PyCharm, it works.
Can someone help me out with this problem? Would be grateful! :)

Maybe this is because what we export from python is modules not packages.
I think this issue arises due to that.
Also, to run the same in cmd, one can follow this syntax:
from InnerPackage2.InnerInnerPackage6 import InnerInnerPackage6
This might be the reason, the difficulty arises when we run the same program in both JetBrains PyCharm and on cmd.

Related

How to import EF 3.0 method in Brightway2?

My colleague, after the recent update of Brightway2, can see EF3.0 method within the availeable.
I tried to do the same but it's not working (I have some new methods, but not EF3.0).
This is what I have done:
Conda update conda
Conda update brightway2
In Brightway
import brightway2 as bw
bw.Database('biosphere3').delete()
bw.Database('biosphere3').deregister()
bw.projects
bw.projects.delete_project('Name of my project',delete_dir=True)
bw.projects.report()
bw.databases
bw.databases.clear()
bw.bw2setup() #Import of biosphere3
# Import ecoinvent 3.7
ei37dir ="*my directory*"
if 'ecoinvent 3.7_cutoff' in bw.databases:
print("Database has already been imported")
else:
ei37 = bw.SingleOutputEcospold2Importer(ei37dir, 'ecoinvent 3.7_cutoff')
ei37.apply_strategies()
ei37.statistics()
ei37.drop_unlinked(True)
ei37.write_database()
list(bw.methods)
How can I implement EF3.0?
Thank you in advance
Kevin
The EF method was added in bw2io version 0.8.6. You would need to update to this library version, and then reinstall the LCIA methods (doesn't have anything to do with which version of ecoinvent you have, LCIA methods are separate).
In a new project, just calling bw2setup() should be fine. In an older project, you will need to rewrite both biosphere flow list and the LCIA methods:
import bw2io as bi
bi.create_default_biosphere3(overwrite=True)
bi.create_default_lcia_methods(overwrite=True)

Audio issue with gTTS

I'm trying to code Jarvis.
I'm having a problem with my audio output.
when I run the python script, it said that I don't have OS imported.
How would I solve this issue?
-Many Thanks
It seems like your Python script needs to import
the OS library
import os
Here's a few example lines you can use:
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>> statinfo.st_size
264

how to give ctrl+c command in robot framework

In Robot Framework how do I give the ctrl+c command?
I have tried this line but it does not work
${crtl_c} Evaluate chr(int(3)) SSHLibrary.Write Bare ${crtl_c}
Use imagehorizon as a library :
Press Combination KEY.CTRL C
Use PyAutoGUI
PyAutoGUI works on Windows/Mac/Linux on Python 2 & 3. Install from PyPI with
pip install pyautogui
import pyautogui
def CntrlC():
pyautogui.hotkey('ctrl', 'c') #Performs ctrl+c
Now just import the py file and use CntrlC as the Keyword
${ctrl_c} evaluate chr(int(3))
SSHLibrary.Write Bare ${crtl_c}
Or else you can give the line in variables section:
***variable***
${ctrl_c} evaluate chr(int(3))
Just got this working. The problem with the answers above is that you need an equal sign.
${ctrl-c}= evaluate chr(int(3))
Write Bare ${ctrl-c}
Refering to a previous answer on an SO question where if you're on windows, the SendKeys python library is used to send actual key presses to the system. In case you're on a linux based system it pretty much depends on the GUI you're using and a few other factors. This SO Question has some good content that might help you.

getMethodASTEclipse() returns undeclared variable

I am completely new to Rascal and am trying to create ASTs from an eclipse project using the following code
Module FirstTryAST
import lang::java::m3::Core;
import lang::java::jdt::m3::Core;
import Set;
import Relation;
import IO;
import List;
import Map;
import Exception;
import ParseTree;
void test(){
M3 myModel = createM3FromEclipseProject(|project://MyProject/|);
println("Loaded M3 model, looping through methods..");
for(m <- methods(model)) mAST = getMethodASTEclipse(m);
println("Success");
}
When the program (run in eclipse Rascal Console) tries to execute
getMethodASTEclipse(m);
it returns:
|plugin://rascal_eclipse/src/org/rascalmpl/eclipse/library/lang/java/jdt/m3/Core.rsc|(1238,18,<40,12>,<40,30>):
Undeclared variable: getModelContaining
How do I get around this / what did I do wrong ?
I am using Eclipse Mars on Ubuntu 15.04 (Cinnamon).
If you need more information, please let me know.
Update:
When I use getMethodASTEclipse(m, model = myModel) it works fine.
Although this workaround works for me, I still would like to know the answer on why I get this undeclared variable message.
This has been translated into an issue on github. This was a bit of an unused function, and I think we will delete it.
To get the AST use either lang::java::jdt::m3::AST::createAstsFromEclipseProject or lang::java::jdt::m3::AST::createAstsFromEclipseFile. With rascal pattern matching you can find the methods inside.

How can I set up default startup commands in iPython notebooks?

I want to put couple of cells with commands I need in almost every new notebook in every new notebook I create.
For example when I create a new notebook it should put a
%matplotlib inline
import matplotlib.pyplot as plt
in a cell by default but not execute it.
How could I set something like that up?
This will work for both terminal based IPython shell and Browser based Notebook:
Navigate to ~/.ipython/profile_default
Create a folder called startup if it’s not already there
Add a new Python file called start.py
Put your favorite imports (and custom functions may be) in this file
Launch IPython or a Jupyter Notebook and your favorite libraries will be automatically loaded every time!
Here is my sample for start.py:
Another Source
To define set of commands on default startup, you need to add the commands in the templete ipy_user_conf.py file in your ~/.ipython directory.
This module is imported during IPython startup. So you can easily do : import modules, configure extensions, change options, define magic commands, put variables and functions in the IPython namespace etc.
Here is the sample ipy_user_conf.py :
# Most of your config files and extensions will probably start
# with this import
import IPython.ipapi
ip = IPython.ipapi.get()
# You probably want to uncomment this if you did %upgrade -nolegacy
# import ipy_defaults
import os
def main():
#ip.dbg.debugmode = True
ip.dbg.debug_stack()
# uncomment if you want to get ipython -p sh behaviour
# without having to use command line switches
import ipy_profile_sh
import jobctrl
# Configure your favourite editor?
# Good idea e.g. for %edit os.path.isfile
#import ipy_editors
# Choose one of these:
#ipy_editors.scite()
#ipy_editors.scite('c:/opt/scite/scite.exe')
#ipy_editors.komodo()
#ipy_editors.idle()
# ... or many others, try 'ipy_editors??' after import to see them
# Or roll your own:
#ipy_editors.install_editor("c:/opt/jed +$line $file")
o = ip.options
# An example on how to set options
#o.autocall = 1
o.system_verbose = 0
#import_all("os sys")
#execf('~/_ipython/ns.py')
# -- prompt
# A different, more compact set of prompts from the default ones, that
# always show your current location in the filesystem:
#o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Normal\n\C_Green|\#>'
#o.prompt_in2 = r'.\D: '
#o.prompt_out = r'[\#] '
# Try one of these color settings if you can't read the text easily
# autoexec is a list of IPython commands to execute on startup
#o.autoexec.append('%colors LightBG')
#o.autoexec.append('%colors NoColor')
o.autoexec.append('%colors Linux')
# some config helper functions you can use
def import_all(modules):
""" Usage: import_all("os sys") """
for m in modules.split():
ip.ex("from %s import *" % m)
def execf(fname):
""" Execute a file in user namespace """
ip.ex('execfile("%s")' % os.path.expanduser(fname))
main()
For more details, please refer the link : Customization of IPython.
I hope this is what you wanted to know.
JupyterLab
In a comment to one of the other answers, the OP pointed out the need to insert the actual code instead of having it load in the background. One way is to create a text keyboard shortcut by going to Settings -> Advanced settings editor -> JSON settings Editor and adding the following under User Preferences:
{
"shortcuts": [
{
"command": "apputils:run-first-enabled",
"selector": "body",
"keys": ["Alt I"],
"args": {
"commands": [
"console:replace-selection",
"fileeditor:replace-selection",
"notebook:replace-selection",
],
"args": {"text": "import pandas as pd\nimport altair as alt\n\n"}
}
}
]
}
This will insert the following snippet each time you press Alt + i in the notebook:
import pandas as pd
import altair as alt
# <-- Cursor placed here
More on text shortcuts in jupyterlab
IPython console
If you are interested in automatically importing commonly used libraries in the IPython console only so that they are there for interactive use, but not in the notebook to avoid issues with sharing notebooks lacking some imports, you can launch IPython like so (and set up an alias to not have to type this each time):
ipython -c "import pandas as pd; import numpy as np" -i
(This was what I was looking for when I originally found this question)

Resources