How to call other python script in another python script? - python

I am trying to call other python script to another python script using import but it is giving some error. Can you please help me how to do this?
Example:
case.py is my one script which have one one function generate_case('rule_id'). This function is returning some value.
final.py is my another script in which I am trying to call above script and store return value into a variable.
I am trying to do in python :
import case as f_case
qry = ''
qry += f_case.generate_case('R162')
print(qry)
Error:
ModuleNotFoundError: No module named 'case'
Both the scripts are available in the same location.

Try this
import os
import sys
scriptpath=''
sys.path.append(os.path.abspath(scriptpath))
# Do the import
import case as f_case

I rename the script as new_cons.py. Now it working for me. May be in script name I have added integer so it is not importing the script.

Related

cannot import name X from module

Edit: The problem was solved. There was another cmd.py in the python search path. Thank you #Barmar!
I wanted to divide my chunky python script into separate modules but I have encountered an error when importing. For some reasons, it even fails to import a very simple function named Hi() from a very simple script.
I checked with Linter and it doesn't find any problem with it. The error always comes up on runtime. Any solutions?
gamemode.py:
from samp import decode
from samp import SetGameModeText
from cmd import Hi
import s
import sqlite3
Hi()
cmd.py:
def Hi():
return print("Hi")
(This is the whole script)
Output:
ImportError: cannot import name 'Hi' from 'cmd'

Cannot import function from another file

I have a file called hotel_helper.py from which I want to import a function called demo1, but I am unable to import it.
My hotel_helper.py file:
def demo1():
print('\n\n trying to import this function ')
My other file:
from hotel.helpers.hotel_helper import demo1
demo1()
but I get:
ImportError: cannot import name 'demo1' from 'hotel.helpers.hotel_helper'
When I import using from hotel.helpers.hotel_helper import * instead of from hotel.helpers.hotel_helper import demo1 it works and the function gets called. I tried importing the whole file with from hotel.helpers import hotel_helper and then call the function with hotel_helper.demo1() and it works fine. I don't understand what's wrong in first method. I want to directly import function rather using * or importing the whole file.
If you filename is hotel_helper.py you have to options how to import demo1:
You can import the whole module hotel_helper as and then call your func:
import hotel_helper as hh
hh.demo1()
You can import only function demo1 from module as:
from hote_helpers import demo1
demo1()
From your fileName import your function
from hotel.helpers import demo1
demo1()
You can import a py file with the following statement:
# Other import
import os
import sys
if './hotel' not in sys.path:
sys.path.insert(0, './hotel')
from hotel import *
NOTE:
For IDE like PyCharm, you can specify the import path using the Project Structure setting tab (CTRL+ALT+S)
Helpful stack overflow questions [maybe off topic]:
What is the right way to create project structure in pycharm?
Manage import with PyCharm documentation:
https://www.jetbrains.com/help/pycharm/configuring-project-structure.html
This is probably a duplicate of: https://stackoverflow.com/posts/57944151/edit
I created two files (defdemo.py and rundefdemo.py) from your posted 2 files and substituted 'defdemo' for 'hotel.helpers.hotel_helper' in the code. My 2 files are in my script directory for Python 3.7 on windows 10 and my script directory is in the python path file python37._pth. It worked.
defdemo.py
def demo1():
print('\n\n trying to import this function ')
rundefdemo.py
from defdemo import demo1
demo1()
output
trying to import this function
I was able to solve the issue, it was related to some imports I was making in my file, when I removed all the import statement in my hotel_helper.py ,the code started working as expected , Still I don't understand reason why the issue was occurring. anyway it works.
This ImportError can also arise when the function being imported is already defined somewhere else in the main script (i.e. calling script) or notebook, or when it is defined in a separate dependency (i.e. another module). This happens most often during development, when the developer forgets to comment out or delete the function definition in the body of a main file or nb after moving it to a module.
Make sure there are no other versions of the function in your development environment and dependencies.

how to import scripts as modules in ipyhon?

So, I've two python files:
the 1st "m12345.py"
def my():
return 'hello world'
the 2nd "1234.py":
from m12345 import *
a = m12345.my()
print(a)
On ipython I try to exec such cmds:
exec(open("f:\\temp\\m12345.py").read())
exec(open("f:\\temp\\1234.py").read())
the error for the 2nd command is:
ImportError: No module named 'm12345'
Please, help how to add the 1st file as a module for the 2nd?
First off, if you use the universal import (from m12345 import *) then you just call the my() function and not the m12345.my() or else you will get a
NameError: name 'm12345' is not defined
Secondly, you should add the following snippet in every script in which you want to have the ability of directly running it or not (when importing it).
if "__name__" = "__main__":
pass
PS. Add this to the 1st script ("m12345.py").
PS2. Avoid using the universal import method since it has the ability to mess the namespace of your script. (For that reason, it isn't considered best practice).
edit: Is the m12345.py located in the python folder (where it was installed in your hard drive)? If not, then you should add the directory it is located in the sys.path with:
import sys
sys.path.append(directory)
where directory is the string of the location where your m12345.py is located. Note that if you use Windows you should use / and not \.
However it would be much easier to just relocate the script (if it's possible).
You have to create a new module (for example m12345) by calling m12345 = imp.new_module('m12345') and then exec the python script in that module by calling exec(open('path/m12345.py').read(), m12345.__dict__). See the example below:
import imp
pyfile = open('path/m12345.py').read()
m12345 = imp.new_module('m12345')
exec(pyfile, m12345.__dict__)
If you want the module to be in system path, you can add
sys.modules['m12345'] = m12345
After this you can do
import m12345
or
from m12345 import *

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)

python/jython NameError

im facing typical NameError (without any additional message) on command "cd" while importing other file.
E.g. executor.py
import sys
from java.lang import System
import ds_update
x = ds_update.DataSource()
x.someAction()
And ds_update.py
import sys
from java.lang import System
import sys
from java.lang import System
class DataSource:
def someAction(self):
try:
cd('/')
...
Got error: (if those commands are in one file, there is no problem with cd)
Problem invoking WLST - Traceback (innermost last):
File "...\executor.py", line 17, in ?
File "...\ds_update.py", line 11, in updateDS
NameError: cd
Thank you:-)
You're trying to use a function that isn't defined, namely cd(), according to your comments, it is something provided by WLST. I never used Jython nor WLST, but you have to find a way to import these methods in your script to be able to use them.
there are a few imports needed, namely at least:
import wl
the way to generate the wl module is described by Oracle here http://docs.oracle.com/cd/E15051_01/wls/docs103/config_scripting/using_WLST.html#wp1094333
then you should prefix with "wl." all your "cd" and other WLST built-in commands.
you will find more here
http://www.javamonamour.org/2013/08/wlst-nameerror-cd.html
Even though it is old, I want to add this:
WLST uses a type of namespace. because of this, functions pertaining to wlst don't work if you put the to-be-imported-files not in /wlserver_10.3/common/wlst

Categories

Resources