How can I run a function I have created in another file? I know there are many questions asking this but my code is so simple I dont get how it doesn't work.
In one file called Testfile I have
def greeting():
print("Hello")
and in the other I have
import Testfile
greeting()
but when I run the code I get the error
"name 'greeting' is not defined"
import Testfile
Testfile.greeting()
or
from Testfile import greeting
greeting()
you have to specify which module the function is coming from with a . or you tell it when you are importing.
You must call the function after the module that contains it:
import Testfile
Testfile.greeting()
Note that this approach is better because this may lead to namespace conflicts and prevents the scalability of your program.
Please follow PEP 8, section module names
Related
I am trying to import just one function from a .py file which has a space in its title. Due to external constraints, I cannot rename the file.
My first try was:
from File 1 import my_func
But that got a SyntaxError. Following advice on other StackOverflow, I found ways to import all the functions from a module/file:
V1:
exec(open("File 1.py").read())
V2:
globals().update(vars(__import__('File 1')))
However, I would like to only import my_func. I would also prefer to do this without using other modules like importlib. Any help is very much appreciated, I am still learning!
Editing the answer as requsted:
Source: How do you import a file in python with spaces in the name?.
Importing single function from a module with spaces in name without using importlib is simply impossible, since your only weapon here is __import__.
Your only option is to import the whole module and only keep functions you like. But it still imports the whole module.
Important notice
Getting rid of spaces and other non-alphanumeric symbols from module names is strongly recommended.
Example
File 1.py
def foo():
print("Foonction.")
def spam():
print("Get out!")
main.py
globals()["foo"] = getattr(__import__("File 1"),"foo")
I am trying to understand how to write your own modules, by trying to create a simple one, but I don't seem to understand how to use the __init__ file, and this whole import stuff works.
So right now I have a package called "helloWorld", and the structure looks like this:
helloWorld
__init__.py
helloWorldFile.py
helloBonjourFile.py
and these are the contents for each file:
__init__.py:
from helloWorldFile import helloWorldClass
helloWorldFile.py:
import helloBonjourFile
class helloWorldClass():
def __init__(self):
self.keyword = 'Hello Beautiful World'
def hello(self):
print self.keyword
helloBonjourFile.run()
helloBounjourFile.py:
def run():
print 'Bonjour Mon Ami!'
So the idea is, i want to run whatever that is in "helloBonjourFile" from "helloWorldFile", so I try running this in a Python shell:
import helloWorld
reload(helloWorld)
helloWorld.helloWorldClass().hello()
It prints out the "Hello Beautiful World" part fine, but after that i keep getting an error:
AttributeError: 'module' object has no attribute 'run'
I am pretty sure I am going about this incorrectly, how do i correctly run both the contents of "helloWorld" and "helloBonjour"? I'd like to keep the file that actually runs these things to a minimum...
I also would like to figure out a way to pass arguments into "helloBonjour" if possible...
I figured this out, for anyone else that may be having similar issues, this was caused by editing one file and trying to run from the custom module in the same environment, and was solved by running a reload() command for every file. but you have to do it in the order of files being imported, in my case i had to reload in the following order:
reload(helloBounjourFile)
reload(helloWorldFile)
reload(helloWorld)
and that should do the trick.... if it doesnt try it a few times more for it to refresh (at least that worked for me)...
I have a requirement where I need to parse the functions defined in a python file from another python file.
e.g. I have a python file with following contents:
a.py
import os, sys
def function1('text'):
pass
def function2('text'):
pass
Another file is:
b.py
interested_func = 'function2'
function_list = <code to fetch the functions defined in a.py>
if interested_func in function_list:
print 'match found'
How can I get the functions from a.py into b.py so that I can compare the same with the 'interested_func' data and can do specific task based on the match.
Please note that I have 100s of files with different functions defined inside them, so I do not want to import the file.
Please help, thanks in advance!
You should probably use the importlib module:
import importlib
obj = importlib.import_module(module)
print(dir(obj))
You can read more about importlib over in the Python docs.
If that doesn't work for you, then you'll probably want to look at some static code analysis tools such as pylint that might give you a clue into how to do this sort of thing. Another place to look would be to check out PyDev's source code and see how it does code analysis.
I am working on project euler and wanted to time all of my code. What I have is directory of files in the form 'problemxxx.py' where xxx is the problem number. Each of these files has a main() function that returns the answer. So I have created a file called run.py, located in the same directory as the problem files. I am able to get the name of the file through command prompt. But when I try to import the problem file, I continue to get ImportError: No module named problem. Below is the code for run.py so far, along with the command prompt used.
# run.py
import sys
problem = sys.argv[1]
import problem # I have also tired 'from problem import main' w/ same result
# will add timeit functions later, but trying to get this to run first
problem.main()
The command prompts that I have tried are the following: (both of which give the ImportError stated above)
python run.py problem001
python run.py problem001.py
How can I import the function main() from the file problem001.py? Does importing not work with the file name stored as a variable? Is there a better solution than trying to get the file name through command prompt? Let me know if I need to add more information, and thank you for any help!
You can do this by using the __import__() function.
# run.py
import sys
problem = __import__(sys.argv[1], fromlist=["main"]) # I have also tired 'from problem import main' w/ same result
problem.main()
Then if you have problem001.py like this:
def main():
print "In sub_main"
Calling python run.py problem001 prints:
In sub_main
A cleaner way to do this (instead of the __import__ way) is to use the importlib module. Your run.py needs to changes:
import importlib
problem = importlib.import_module(sys.argv[1])
Alternatives are mentioned in this question.
For sure! You can use __ import_ built-in function like __import__(problem). However this is not recommended to use, because it is not nice in terms of coding-style. I think if you are using this for testing purposes then you should use unittest module, either way try to avoid these constructions.
Regards
You can use exec() trick:
import sys
problem = sys.argv[1]
exec('import %s' % problem)
exec('%s.main()' % problem)
I cant figure out how to add my simple function to my main program file. why not ?
when i do this:
import print_text
echothis("this is text")
exit()
cant understand why people think this is such a bad question.
this doesnt work either:
print_text.echothis("this is text")
same thing happens if i type any of the answers below.
including:
from print_text import echothis
I just get this error:
from: can't read /var/mail/print_text
./blah3.py: line 3: syntax error near unexpected token `"this is text"'
./blah3.py: line 3: `print_text.echothis("this is text")'
or a variant without the /var/mail line...
*this file is named print_text.py*
#!/usr/bin/env python
import time
import random
import string
import threading
import sys
def echothis(txt):
woo=txt
stdout.write(woo)
EDIT: You're actually not having a python issue but a bash one. You're running your python script as if it were bash (hence the 'from: can't read from'), did you put #!/usr/bin/env python at the beginning of the file you're running (not print_text.py, the other one)? You could alternatively call it that way: python myfile.py and it should work.
When you import a module, it is namespaced, so if you want to use anything that is from that module, you need to call it using the proper namespace. Here, you would call you echothis function using print_text.echothis.
Alternatively, if you want to include echothis in your main namespace, you can use the from print_text import echothis syntax.
Try this:
import print_text
print_text.echothis("this is a text")