Using my Python program - python

I'm really new to python and I have made the following program:
class AddressBook:
def __init__(self):
self.b = {}
def insert(self,name, phone):
self.b[name]=phone
print "I am confused"
def get(self,name):
return self.b[name]
def has_name(self,name):
return self.b.has_key(name)
def list(self):
for n,p in self.b.iteritems():
print n,p
def delete(self, name):
del self.b[name]
def orderedList(self):
orderedkeys = self.b.keys()
orderedkeys.sort()
for n in orderedkeys:
print n, self.b[n]
I now want to compile it test it out in terminal to see if it all works.
I went to the directory and compiled it with
python address.py
Now I want to add things to the list, print the contents of the list, delete them (pretty much play around with my program) but I don't know how...
After compiling, how do I manually test (play around) with my python program?
Thanks in advance.

Python is an interpreted language, and .py files do not require direct compilation. There are a few ways to run Python code, but for "playing around" you can simply activate the Python interpreter and import the class.
In a command prompt:
> python
In Python:
>>> from address import AddressBook
>>> a = Addressbook()
>>> a.insert("Jenny", "867-5309")
>>> a.get("Jenny")
'867-5309'

The python script is not compiled. At least not in ways as other languages, like Fortran and C. From this answer:
Python has a compiler! You just don't notice it because it runs automatically. You can tell it's there, though: look at the .pyc (or .pyo if you have the optimizer turned on) files that are generated for modules that you import.
Also, it does not compile to the native machine's code. Instead, it compiles to a byte code that is used by a virtual machine. The virtual machine is itself a compiled program. This is very similar to how Java works; so similar, in fact, that there is a Python variant (Jython) that compiles to the Java Virtual Machine's byte code instead! There's also IronPython, which compiles to Microsoft's CLR (used by .NET). (The normal Python byte code compiler is sometimes called CPython to disambiguate it from these alternatives.)
You have two ways to test it out:
type python -i address.py in the terminal. This will run the script and enter the python shell.
You enter the python shell and then type from address.py import AddressBook.
On both ways, you can
play around with your code.

Related

For what uses do we need `sys` module in python?

I'm a bit experienced without other languages but, novice with Python. I have come across made codes in jupyter notebooks where sys is imported.
I can't see the further use of the sys module in the code. Can someone help me to understand what is the purpose of importing sys?
I do know about the module and it's uses though but can't find a concise reason of why is it used in many code blocks without any further use.
If nothing declared within sys is actually used, then there's no benefit to importing it. There's not a significant amount of cost either.
Sys module is a rather useful module as it allows you to work with your System and those things. Eg:
You can access any command line arguments using sys.argv[1:]
You can see the Path to files.
Version of your Python Interpreter using sys.version
Exit the running code with sys.exit
Mostly you will use it for accessing the Command Line arguments.
I'm a new pythonista bro, I learned to import it whenever I want to exit the program with a nice exit text in red
import sys
name = input("What's your name? ")
if name == "Vedant":
print(f"Hello There {name}.")
else:
sys.exit(f"You're not {name}!")
The sys includes "functions + variable " to help you control and change the python environment #runtime.
Some examples of this control includes:
1- using other sources data as input via using:
sys.stdin
2- using data in the other resources via using:
sys.stdout
3- writing errors when an exception happens, automatically in :
sys.stderr
4- exit from the program by printing a message like:
sys.exit("Finish with the calculations.")
5- The built-in variable to list the directories which the interpreter will looking for functions in them:
sys.pasth
6- Use a function to realize the number of bytes in anonymous datatype via:
sys.getsizeof(1)
sys.getsizeof(3.8)

Exposing a Python Class to COM/VBA

I have a simple python class that I am trying to make com-accessible (e.g., to VBA):
class Foo(object):
_reg_progid_ = 'Foo.Application'
_reg_clsid_ = '{602462c5-e750-4d1c-879b-a0465bebb526}'
_public_methods_ = ['say_hello']
def __init__(self):
pass
def say_hello(self, name):
return f'Hello, {name}'
if __name__=='__main__':
print("Registering COM server")
import win32com.server.register
win32com.server.register.UseCommandLine(Foo)
Several examples indicate this is a pretty standard approach (see here and here).
From python, this appears to be com-accessible. No errors raise, and the output appears as expected:
from comtypes.client import CreateObject
f = CreateObject('Foo.Application')
f.say_hello('David')
When trying to instantiate a Foo from VBA, however, there is an error (Run-time error -2147024770 (8007007e) Automation error The specified module could not be found).
Dim f As Object
Set f = CreateObject("Foo.Application")
I am actually able to resolve this error using the method described in this answer (and this one), specifically doing:
_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
And then localserver.serve('{602462c5-e750-4d1c-879b-a0465bebb526}') in the name guard function.
However, in some past applications development work (a long time ago using python 2.7) I know we did not do this part -- instead we used Innosetup to compile an installer from a foo.exe and foo.dll (derived from foo.py probably from py2exe or similar) and other dependencies.
I'm happy (for now) with the solution, but I guess my question is whether this is necessary (as several examples don't do these things) or if there's something else I'm missing (e.g., the installer that I used in a past life actually handled this bit behind-the-scenes with the DLL instead of a .py file?)?
Additional information: OS is 64-bit Windows, running Excel 2013 (32-bit) and python 3.7.4 (32-bit).

PyInstaller: Executable to access user-specified Sourcecode

I'm using pyinstaller to distribute my code as executable within my team as most of them are not coding/scripting people and do not have Python Interpreter installed.
For some advanced usage of my tool, I want to make it possible for the user to implement a small custom function to adjust functionality slightly (for the few experienced people). Hence I want to let them input a python file which defines a function with a fixed name and a string as return.
Is that possible?
I mean the py-file could be drag/dropped for example, and I'd tell them that their user-defined function needs to have a certain name, e.g. "analyze()" - is it now possible to import that from the drag/dropped pythonfile within my PyInstaller Script and use it as this?
I know, it certainly will not be safe/secure and they could do evil things, delete files and so one... But that are things which we don#t care at this point, please no discussions about it. Thanks!
To answer my own question: yes it does actually work to import a module/function from a given path/pythonfile at runtime (that I knew already) even in PyInstaller (that was new for me).
I used this for my Py2.7 program:
f = r'C:\path\to\userdefined\filewithfunction.py'
if os.path.exists(f):
import imp
userdefined = imp.load_source('', f) # Only Python 2.x, for 3.x see: https://stackoverflow.com/a/67692/701049
print userdefined # just a debugging print
userdefined.imported() # here you should use try/catch; or check whether the function with the desired name really exists in the object "userdefined". This is only a small demo as example how to import, so didnt do it here.
filewithfunction.py:
--------------------
def imported():
print 'yes it worked :-)'
As written in the comments of the example code, you'll need a slightly different approach in Python 3.x. See this link: https://stackoverflow.com/a/67692/701049

python "up-button" command completion, matlab/julia style [duplicate]

This question already has answers here:
Python REPL tab completion on MacOS
(2 answers)
Closed 7 years ago.
I recently switched from Matlab to Numpy and love it. However, one really great thing I liked about Matlab was the ability to complete commands. There are two ways that it does this:
1) tab completion. If I have a function called foobar(...), I can do 'fo' and it will automatically fill in 'foobar'
2) "up-button" completion (I'm not sure what to call this). If I recently entered a command such as
'x = linspace(0, 1, 100); A = eye(50);'
and then I wish to quickly type in this same command so that I can re-evaluate it or change it slightly, then I simply type 'x =' then press up and it will cycle through all previous commands you typed that started with 'x ='. This was an awesome awesome feature in Matlab (and if you have heard of Julia, it has done it even better by allowing you to automatically re-enter entire blocks of code, such as when you are defining functions at the interactive prompt)
Both of these features appear to not be present in the ordinary python interactive shell. I believe tab autocomplete has been discussed before and can probably be enabled using the .pythonrc startup script and some modules; however I have not found anything about "up-button" completion. Python does have rudimentary up-button functionality that simply scrolls through all previous commands, but you can't type in the beginning of the command and have that narrow down the range of commands that are scrolled through, and that makes a huge difference.
Anyone know any way to get this functionality on the ordinary python interactive shell, without going to any fancy things like IPython notebooks that require separate installation?
Tab completion is not a standard feature of the python 2.x interpreter. It is possible that a particular distribution (intending, Linux distribution) ships with initialization files that enable tab completion. On the other hand, python 3.x has autocompletion enabled by default.
To enable tab completion in 2.x, you need to instruct the interpreter about loading some startup code, using an environment variable
export PYTHONSTARTUP=$HOME/.whatever
The code that you want to put into the startup file varies, but for enabling tab completion the docs have
try:
import readline
except ImportError:
print "Module readline not available."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
Coming eventually to your ast question, what you named “up-button” command completion, matlab/julia style, IPython has it and I'm not aware of a module that implements it, even if it seems to me that I read something on such a beast on comp.lang.python some month ago.
In your question you reference IPython's notebook... It may be necessary to remind that you don't need the notebook interface to use IPython, it can be used to its full potential even in a text console.
Use iPython or some other Python shell. There are plenty. You may even program your own that will do whatever you want.
tab completion. If I have a function called foobar(...), I can do 'fo' and it will automatically fill in 'foobar'
Really? Which version of Python are you using and how did you get it? It works for me on a regular python shell for both windows and Linux with both python 2.7 and python 3.4. It sounds like your version of Python might not have been built with readline support, which I think is required for this sort of thing.
This is what I tried:
>>> sup
after tab becomes:
>>> super(
"up-button" completion (I'm not sure what to call this). If I recently entered a command such as 'x = linspace(0, 1, 100); A = eye(50);' and then I wish to quickly type in this same command so that I can re-evaluate it or change it slightly, then I simply type 'x =' then press up and it will cycle through all previous commands you typed that started with 'x ='.
It is called a "History search", and it also works for me in the default Python shell in both windows and Linux. Again, I think this requires readline.
>>> a = 'test'
>>> a
Then I press up, and I get:
>>> a = 'test'
You can also press Ctrl+r, then start typing. This will search the history for the last command that includes what you typed. So, for example:
>>> a = 'test'
>>> b = 5
>>> c = a
Then ctrl+r:
>>>
forward-i-search1`b: b = 5
Then hit Enter to execute that command.
>>>
>>> b = 5
>>>
If the match isn't what you want, you can type more, or hit Ctrl+r again and again to cycle through the matches.
Edit:
It looks like this is a known problem with the built-in Mac Os X version of Python. It doesn't come with readline due to readline being GPL. Instead it includes libedit, which is not fully compatible. There are instructions on how to get it working on Mac Os X here

How do I invoke Python code from Ruby?

Does a easy to use Ruby to Python bridge exist? Or am I better off using system()?
You could try Masaki Fukushima's library for embedding python in ruby, although it doesn't appear to be maintained. YMMV
With this library, Ruby scripts can directly call arbitrary Python modules. Both extension modules and modules written in Python can be used.
The amusingly named Unholy from the ingenious Why the Lucky Stiff might also be of use:
Compile Ruby to Python bytecode.
And, in addition, translate that
bytecode back to Python source code
using Decompyle (included.)
Requires Ruby 1.9 and Python 2.5.
gem install rubypython
rubypython home page
I don't think there's any way to invoke Python from Ruby without forking a process, via system() or something. The language run times are utterly diferent, they'd need to be in separate processes anyway.
If you want to use Python code like your Python script is a function, try IO.popen .
If you wanted to reverse each string in an array using the python script "reverse.py", your ruby code would be as follows.
strings = ["hello", "my", "name", "is", "jimmy"]
#IO.popen: 1st arg is exactly what you would type into the command line to execute your python script.
#(You can do this for non-python scripts as well.)
pythonPortal = IO.popen("python reverse.py", "w+")
pythonPortal.puts strings #anything you puts will be available to your python script from stdin
pythonPortal.close_write
reversed = []
temp = pythonPortal.gets #everything your python script writes to stdout (usually using 'print') will be available using gets
while temp!= nil
reversed<<temp
temp = pythonPortal.gets
end
puts reversed
Then your python script would look something like this
import sys
def reverse(str):
return str[::-1]
temp = sys.stdin.readlines() #Everything your ruby programs "puts" is available to python through stdin
for item in temp:
print reverse(item[:-1]) #Everything your python script "prints" to stdout is available to the ruby script through .gets
#[:-1] to not include the newline at the end, puts "hello" passes "hello\n" to the python script
Output:
olleh
ym
eman
si
ymmij
For python code to run the interpreter needs to be launched as a process. So system() is your best option.
For calling the python code you could use RPC or network sockets, got for the simplest thing which could possibly work.

Categories