I'm trying to figure out xlwings. I have the following python code:
from xlwings import xlfunc
from datetime import timedelta, datetime
#xlfunc
def convert(gmt):
gmtValue = datetime(int(gmt[6:10]), int(gmt[3:5]), int(gmt[0:2]), int(gmt[11:13]), int(gmt[14:16]), int(gmt[17:19]))
localTime = gmtValue - timedelta(seconds=(6*3600))
return localTime
All it does is take a time stamp string such as 05/01/2016 14:25:56 GMT and pulls off the GMT and converts it into local time (central time for the US.) I'm trying to use that code along with:
Sub convertToLocal()
RunPython(“import converToLocal; convertToLocal.convert(gmt)”)
End Sub
To make a user defined function but Excel doesn't seem to recognize the python code even though I have the xlwings.bas module imported. The only error I get is “Compile error: Expected end of Statement.” Which I think just means Excel doesn't recognize the python code. Any idea how to fix it? Also, what is the correct way to pass the contents of a cell into the python code?
RunPython and the decorator syntax are two different approaches. To do user defined functions with decorators, follow the guide here. You ll need to import those function with the add-in, no RunPython needed.
Related
I'm using Python inside Pycharm, and wanting to scheduling code to run to open a workbook and save every day at a specified time. The function I've written to open and save the workbook has been working properly, but I'm now running in to two issues.
I cannot Import time, it's greying out and I'm not sure why
I'm receiving error "AttributeError: 'function' object has no attribute 'day'", and I'm not sure why. error occurs at ".day" within schedule function
import schedule
import time
def Date_Table():
from openpyxl import load_workbook
wb = load_workbook(r'file path')
wb.save(r'file path')
schedule.every.day.at("1:00").do(Date_Table)
I reviewed the functions in the "schedule" package. You just need to correct some syntax. Instead of:
schedule.every.day.at("1:00").do(Date_Table)
you probably want:
schedule.every().day.at("01:00").do(Date_Table)
Note the parentheses in the function call.
Hope that helps.
Regards.
How do I create a header file in python ?
I know the steps to do it in C++ but I don't know how to do it in python.
You can do something like this:
create a new python file (e.g.: pseudo_header) here you can add function, variables etc.
Example - in pseudo_header:
name = "Bob"
in your main.py do this:
import pseudo_header
print(pseudo_header.name) << "Bob"
pseudo_header.name = "John"
print(pseudo_header.name) << "John"
Python is not having header files like c++. Instead we import libraries here.
For example take below small piece of code.
import datetime
print datetime.datetime.now()
Output
2019-11-15 12:33:33.177000
Here we are importing library datetime. datetime.datetime.now() will give you the current date.
You can also import only a specific object instead of whole module. Like below.
from datetime import datetime
print datetime.now()
There is no need to define anything before code in python as we did in c++.
You just know about the syntax of the python it will be enough for beginner programming.
But if you want to use some extra libraries then you will need some importing.
Example
print("Hello World")
output
>> Hello World
Similarly you can define variables, do some conditional programming or define some loops etc.
Example
a = 5
if a != 5:
print("I am angry")
if a == 5:
print("I am happy")
output
>> I am happy
See there is no need to do any importing.
But if you want to use some libraries like. DateTime
import datetime
print datetime.datetime.now()
This library deals with date and time and anythings belongs to them.
That is python :)
What I usually do is create a separate library file with all function definitions and import this in the main script.
Let's say my library is called foo.py, which contains
import numpy as np
def side(area):
'''
Function to get length of the side of a square of a given area.
'''
assert (area > 0), 'Invalid input!'
return np.sqrt(area)
Then, in my main script, I just import the library and use the functions.
import numpy as np
from foo import *
area = 100
print (side(area)) # returns 10
May not be the best way but works for me.
I want to run a vba macro that has IRibbonControl as a parameter using Python win32com.
For example, my vba sub is looks like below
Public Sub test(control As IRibbonControl)
blabla
End Sub
And
And then Python calls test sub using win32com.
What should we put on parameters of a test function?
import os
import win32com.client
from win32com.client import DispatchEx
xl = DispatchEx('Excel.Application')
xl.Workbooks.Open("myexcelfile.xlsm")
xl.Application.Run("test", some magic needs here)
You would need an object on python-side that implements IRibbonControl, and pass that as parameter back to Excel.
The only way I can imagine this makes sense (but I have an open mind) is if you implement a COM add-in (https://support.microsoft.com/en-us/kb/291392) as IDTExensibility2. Then you will be called the OnConnection method (in your python COM server), which gives you the Excel application object.
From there, you could very likely obtain a reference to the ribbon control.
I must admit that I did so far not manage to get any python COM Excel add-in to work myself, though I tried.
Or can you not better obtain the IRibbonControl from the excel application from within the sub, and remove it from the argument list?
Usually that argument is to capture customized Ribbons calls, incoming from the ribbon.
If you are using Python, then you are not using Ribbon, and then you can bypass that, this does not apply to all use cases, although it applies to mine and most also.
Public Sub test(Optional control As IRibbonControl)
blabla
End Sub
Simply using the argument as optional could help there.
import os
import win32com.client
from win32com.client import DispatchEx
xl = DispatchEx('Excel.Application')
xl.Workbooks.Open("myexcelfile.xlsm")
xl.Application.Run("test")
In Python 2.7, I'm getting
'module' has no attribute
, and/or
'name' is not defined
errors when I try to split up a large python file.
(I have already read similar posts and the Python modules documentation)
Say you have a python file that is structured like this:
<imports>
<50 global variables defined>
<100 lengthy functions that each use most or all of the globals
defined above, and also call each other>
<main() that calls some of the functions and uses the globals>
So I can easily categorize groups of functions together, create a python file for each group, and put them there. The problem is whenever I try to call any of them from the main python file, I get the errors listed above. I think the problem is related to circular dependencies. Since all of the functions rely on the globals, and each other, they are circularly dependent.
If I have main_file.py, group_of_functions_1.py, and group_of_functions_2.py,
main_file.py will have:
import group_of_functions_1.py
import group_of_functions_2.py
and group_of_functions_1.py will have
import main_file.py
import group_of_functions_2.py
and group_of_functions_2.py will have
import main_file.py
import group_of_functions_1.py
Regardless of whether I use "import package_x" or "from package_x import *" the problem remains.
If I take the route of getting rid of the globals, then most of the functions will have 50 parameters they will be passing around which then also need to be returned
What is the right way to clean this up?
(I have already read similar posts and the Python modules documentation)
One of the sources of your errors is likely the following:
import group_of_functions_1.py
import group_of_functions_2.py
When importing, you don't add .py to the end of the module name. Do this instead:
import group_of_functions_1
import group_of_functions_2
For teaching purposes I want an IPython notebook that displays (as output from a cell) the function source code, but I want to be able to reference this in multiple notebooks. Hence I would like to display the function code, in a similar way to using the %psource magic, but appropriately syntax highlighted.
This is a similar question to this question, but I want to be able to apply it to a single function within a file, rather than to the complete file at once.
Using the suggestion from the previous question I hacked a short code that works in simple cases:
def print_source(module, function):
"""For use inside an IPython notebook: given a module and a function, print the source code."""
from inspect import getmembers, isfunction, getsource
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
from IPython.core.display import HTML
internal_module = __import__(module)
internal_functions = dict(getmembers(internal_module, isfunction))
return HTML(highlight(getsource(internal_functions[function]), PythonLexer(), HtmlFormatter(full=True)))
Two questions:
This gist suggests that showing the whole function could be done by defining appropriate cell magic. Is it possible to define an appropriate cell magic to just show a single function, as above?
Is there a way of doing this without importing the entire module, or a more robust way of doing this?
1) Magics are just simple function not difficult to define, you could have a look here Customizing IPython - Config.ipynb if I remember correctly. still I'm not sure it is worth definig a magic in your case.
2) Most of the time, no. You have to import the module as we need live code to know where it is defined.
In general, finding the code of a function is not always super easy. On python 3 you can always access the code object, but most of the time, as soon as you have things like decorated function, or dynamically generated function, it becomes difficult. I suppose you could also inspire from psource/pinfo2 and have them return info instead of paging it.