0

I would like to import one python file into another and then compile the main file. How can I do this?

MWE: Suppose I would like to calculate factorial of a positive integer. It can be done successfully by the following way:

n=5
fact = 1
if n < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1,n + 1):
        fact = fact*i
    print "%d!=%d"%(n,fact)

But I would like to create a secondary file say "auxfile.py" containing:

fact = 1
if n < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1,n + 1):
        fact = fact*i
    print "%d!=%d"%(n,fact)

And another main file say "main.py" containing:

print "Required factorial is given below:"
for n in range(30): 
    import auxfile.py

How can I do this?
Note: I know defining a function the whole process can be done in a single file. But I have to do a large program where I would like to apply this process.

BSFU
  • 59
  • 1
  • 7

4 Answers4

0

Simple, just use the import method. To make your life easier simply copy the .py file you would like to import to the same folder that the file you want to import the other code file into is in.

E.g if you wanted to import happy.py to sad.py simply do:

import happy

This would give the following traceback (look at example below):

Hello

Although, this will instantly run everything outside of any def loops in the .py file. Therefore, if you wanted to run a single def loop in the file, then use the following code:

Example contents of happy.py:

print("Hello")
def okay():
    print("okay")

If you did:

happy.okay()

This would give you the following traceback:

Hello
okay

TIP FOR YOUR CODE IN MAIN.PY: You did:

print "Required factorial is given below:" whereas you forgot the brackets. You should use: print("Required factorial is given below:") This will avoid future errors!

Hope this helps!

  • very nice structured answer!! – Sven Apr 16 '20 at 12:05
  • @SnappyPenguin I have tried using import, but occurred errors. I would like to avoid using a function, which is already mentioned in note. – BSFU Apr 16 '20 at 12:11
  • I read your note later on.It's clear. But what is the benefit of your 'inplace import' if a function has the same result? – Mace Apr 16 '20 at 12:19
  • @BSFU there is no reason I can think of why you should be occuring errors. The only thing I can ask is: was it a syntax error? And, if so then check your spelling but otherwise, **check the file you wish to import is in the same folder as the file you wish to actively use to run the other file** – SnappyPenguin Apr 16 '20 at 14:30
  • @Mace I tend to find using functions can get A) confusing in the first place, but in addition they can get too unreliable if you can literally just use import – SnappyPenguin Apr 16 '20 at 14:33
  • @SnappyPenguin, concerning the brackets, the author tagged the post with `python-2.7`. Hence, this syntax is correct. If you want to use print as a function rather than as a keyword in Python 2.7, you have to import `print_function` from `__future__`. After this import, you can use `print` as you would have done in Python 3.X. – Tristan Nemoz Apr 16 '20 at 14:59
  • @SnappyPenguin. It's clear. I was just curious about your considerations. – Mace Apr 16 '20 at 15:24
0

you can do it like this:

auxfile.py

def factorial(n):
    fact = 1
    if n < 0:
        print("Sorry, factorial does not exist for negative numbers")
    elif n == 0:
        print("The factorial of 0 is 1")
    else:
        for i in range(1,n + 1):
            fact = fact*i
            print "%d!=%d"%(n,fact)

in your main.py :

from auxfile import factorial

print "Required factorial is given below:"
for n in range(30): 
    factorial(n)
  • I would like to avoid using a function, which is already mentioned in note.@ArminKazemi – BSFU Apr 16 '20 at 12:13
0

If you're trying to avoid using a function--maybe you could wrap your entire code in the for loop? If it is not as simple as a for-loop, maybe you could copy your main code into the other file above it.

For example: Before:

file1: "Your main code that wants to call the code below"
file2: "Your code that is too cumbersome to convert to a function"

After:
file1:

"Your main code that wants to call the code below"
 for n in range(30):
     "Your code that is too cumbersome to convert to a function"
Samnater
  • 67
  • 5
0

There's still quite an ugly solution, which is to use the exec built-in function.

First of all, you read the code from your file:

with open("auxiliary.py", 'r') as f:
    content = f.readlines()

Then you filter out the lines you don't want, so that content is a string containing your Python code, that is:

# The following evaluates to True
content == 'fact = 1\nif n < 0:\n    print("Sorry, factorial does not exist for negative numbers")\nelif n == 0:\n    print("The factorial of 0 is 1")\nelse:\n    for i in range(1,n + 1):\n        fact = fact*i\n    print "%d!=%d"%(n,fact)'

Then you can just call the exec function, which will act as if the lines were included in lieu of the call of the function:

exec content # Or exec(content), both seems to work in Python 2.7

See here for a further explanation.

Note that you will have access to fact and every other variables, just as if you had written these lines in your main file.

Be aware that this might get dangerous: if you don't formally identify which lines to execute (like, put a comment as an identifier, or if the auxiliary file never changes), you may end up running some code from your auxiliary file you dont want to.

Tristan Nemoz
  • 1,844
  • 1
  • 6
  • 19