简体   繁体   中英

Python cannot import, ImportError: No module named

I am new to python and I am trying to import some values from one file to another. I want my "program" to go from the main_file.py, to other files, like calculator.py, and then comme back to the main_file.py

To do so, I decided I'll make a variable, previously_runned, which has the value 's'. When the calculator would be activated, through the command, it would pick this variable ( and then give it back to the main_file.py, which will check the value of the variable, and then skip some lines of its own script, if the variable previously_runned has the value 's')...:

    import os
    file_path = "calc.py"
    os.system(file_path)

...The calc.py would then pick the variables from main_file.py...:

import previously_runned from main_file

....Which returns:

  File "C:\Users\Kevin\Prog\Calc.py", line 72, in <module>
  import main_file
  ImportError: No module named main_file

Thanks for any help!

When you do os.system() , it's a totally separate Python process; it's not going to share any variables with the Python instance that's actually running the os.system() call. Meaning, if you change previously_runned from calc.py, it wouldn't get reflected in your main file.

What you really want to use here are functions; functions are much better units of control flow than modules. It sounds like you may not have gotten there with Python yet, so I think for now you should sit tight - what you're trying is a good sign that you're doing well, but it's not really going to make sense until you're comfortable defining and calling functions.

Keep at it! Python is pretty awesome.

I want my "program" to go from the main_file.py, to other files, like calculator.py, and then comme back to the main_file.py

Here's a simple example where execution starts in main.py; which calls a function from calc.py. Once the function returns, execution moves back to the next line of main.py

james@brindle:tmp$cat main.py
import calc

value1 = "10"
value2 = "20"

def main():
    sum = calc.add(value1, value2)
    print sum

if __name__ == "__main__":
    main()
james@brindle:tmp$cat calc.py
def add(value_a, value_b):
    print "In ur calc.py, doin ur sumz"
    return value_a + value_b
james@brindle:tmp$python main.py 
In ur calc.py, doin ur sumz
1020

Note that this hasn't made things defined inside main.py accessible from calc.py - it's done the reverse and made things inside calc.py accessible from inside main.py .

As AdamKG already pointed out, you need functions. You have two options, either make calc.py contain the function and import that or include the function in your main file. For example:

main.py

def calc(var1,var2,var3):
    ans1 = var1 + var2
    ...
    return(ans1,ans2,ans3)

var1 = ...
var2 = ...
var3 = ...

ans1,ans2,ans3 = calc(var1,var2,var3)

Probably the best python tutorial/reference I can recommend is the official one at: docs.python.org/tutorial/

I want my "program" to go from the main_file.py, to other files, like calculator.py, and then comme back to the main_file.py

So, in main_file.py , you import calculator , and then call a function defined in calculator.py , and pass the information it needs (variables from main_file ) as parameters to the function.

os.system() executes the command provided as an argument in a subshell. This means that it spawns a new process to execute the command and does not share variables of the calling process. What you want to achieve is better done with classes and functions.

Assuming you have calc.py and main.py in the same folder, here's a simple example of doing this with functions. Please note that this example is only for explanation, it uses bad programming practices like global variables where they can be avoided.

calc.py

var1 = None
var2 = None

def set_variables(a,b):
    global var1, var2
    var1 = a
    var2 = b


def calculate(s):
    if s=='add':
        print var1 + var2
    elif s=='sub':
        print var1 - var2
    elif s=='div':
        print var1/var2
    elif s=='mul':
        print var1*var2
    else:
        print "Invalid Operation"

main.py

from calc import *

set_variables(4,5)
calculate('add')
raw_input()

You can see how we are calling the code in calc.py from main.py without spawning any new process.

Here's another example using classes. This is cleaner, better structured and does not use bad practices like global variables.

calc_class.py

class Calculator:
    def __init__(self,s):
        #init code
        self.s = s

    def __str__(self):
        return self.s

    def add(self,a,b):
        return (a + b)

    def sub(self,a,b):
        return (a-b)

    def div(self,a,b):
        return (a/b)

    def mul(self,a,b):
        return (a*b)

main_class.py

from calc_class import *

calc = Calculator('My Calc')
print calc.add(40,2)
print "My name is %s "%calc

Usage -
d:\\vikesh\\personal\\stuff>python main.py
9

d:\\vikesh\\personal\\stuff>python main_class.py
42
My name is My Calc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM