Accessing a function from a module - python

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")

Related

I got the message: "Bad import syntax:" when I try to import a python function inside my gnuradio flowgraph

I'm trying to do this tutorial on gnuradio page:
https://wiki.gnuradio.org/index.php/TutorialPythonFunctions
It looks to be simple but I got the message "bad import syntax" when I try to import my function "testpy".
Has someone had the same problem or knows how to solve it?
This is unfortunately cryptic. What you have to write in the box is a Python import statement,
not just the name of the module to import. That is, write
import testpy
instead of just testpy.
You can also use from <module> import <name>, <name> and all the other forms of the import statement. (That's why it wants the statement and not just module names: so you can do either kind of import.)

python get the script which imported my script

I want to make my own programming language based on python which will provide additional features that python wasn't provide, for example to make multiline anonymous function with custom syntax. I want my programming language is so simple to be used, just import my script, then I read the script file which is imported my script, then process it's code and stop anymore execution of the script which called my script to prevent error on syntax...
Let say there are 2 py file, main.py and MyLanguage.py
The main.py imported MyLanguage.py
Then how to get the main.py file from MyLanguage.py if main.py can be another name(Dynamic Name)?
Additional information:
I using python 3.4.4 on Windows 7
Like Colonder, I believe the project you have in mind is far more difficult than you imagine.
But, to get you started, here is how to get the main.py file from inside MyLanguage.py. If your importing module looks like this
# main.py
import MyLanguage
if __name__ == "__main__":
print("Hello world from main.py")
and the module it is importing looks like this, in Python 3:
#MyLanguage.py
import inspect
def caller_discoverer():
print('Importing file is', inspect.stack()[-1].filename)
caller_discoverer()
or (edit) like this, in Python 2:
#MyLanguage.py
import inspect
def caller_discoverer():
print 'Importing file is', inspect.stack()[-1][1]
caller_discoverer()
then the output you will get when you run main.py is
Importing file is E:/..blahblahblah../StackOverflow-3.6/48034902/main.py
Hello world from main.py
I believe this answers the question you asked, though I don't think it goes very far towards achieving what you want. The reason for my scepticism is simple: the import statement expects a file containing valid Python, and if you want to import a file with your own non-Python syntax, then you are going to have to do some very clever stuff with import hooks. Without that, your program will simply fail at the import statement with a syntax error.
Best of luck.

Cant run code from imported file

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

Using Numpy from keyword.py

I want to use NumPy in a Python script that uses pandas to process an Excel file. However, one of my constraints is that my file must be named keyword.py, which causes an import error. The import error is traced back to a line from keyword import iskeyword as _iskeyword in C:\Python27\lib\collections.py, which I assume causes an error because my own keyword.py is overriding the default keyword module. Is there any way to avoid this collision?
Not pretty, but a keyword.py of
if True:
import imp, sys
keyword_loc = imp.find_module("keyword", sys.path[1:])[1]
imp.load_source("keyword", keyword_loc)
import collections
print(collections.Counter)
fails with an AttributeError if we replace True with False, but gives me
(2.7) dsm#notebook:~/coding/kw$ python keyword.py
<class 'collections.Counter'>
as is. This works by finding out where the original keyword library is and manually importing it. After this, any following attempts to import keyword will see that it's already there.
For working with a single script, you can remove the current directory from the import search path. That might be sufficient for working on your TopCoder problem, but I wouldn't recommend it as a long-term solution. (Long-term: don't use file names that mirror the standard library.)
If the following script is called keyword.py, it can be run and the import of collections will not trigger an error.
# keyword.py
# Remove the current directory from the import search path
# This is a hack, but it will be sufficient for working with a
# single script that doesn't import any other modules from the
# current directory.
import sys
sys.path = sys.path[1:]
import collections
print(collections)

How can I import a python file through a command prompt?

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)

Categories

Resources