How do I import another script in Python? - python

I'm creating a simple text-based adventure game. I have a long piece of code for combat, but I don't want to copy+paste it every time there's a fight. Is there a way for me to put the combat code into another script, and simply run that whenever combat occurs?

Put that code in a function and save it in another file, in the same directory.
Then in the file where you want to use your function, import the file at the top like:
import newFile
where newFile.py is the name of your file. You do not need .py here. And when you want to use a function from the imported file, use :
newFile.newFunction()

To invoke a pythonsource use the runpy-module:
import runpy
runpy.run_module(
mod_name = "combat.py",
init_globals = None,
run_name = "__main__",
alter_sys = None
)

You are going to do exactly that. First you will put at the top of your code import theScript then your code in that script should be a specific method called possibly doCombat, so you will call theScript.doCombat() in your piece of code.
A great tip that I learned in a computer science class is that if you are ever about to copy and paste code, 90% of the time it should be contained in a method which you should call.

Related

Python file does not recognize imported functions from other Python files

I'm trying to make my code more organized by creating separate files for various functions. I'm testing out printing scenes of dialogue with a text scrolling code, and instead of keeping every line of dialogue in one file, I have moved it to a scene0.py file in the folder scenes. In that file, I define the function playscene0.
In a different folder called scenetext, I have a file called textstuff.py which contains the defined functions print_italics (which prints italics text), texttype (which makes each character type out individually like some video games do), and textscroll (which reads lists of dialog and formats it, plus timings with time.sleep).
That aforementioned scene0.py file uses from scenetext.textstuff import * to import the above functions, plus additional variables that go along with them (unique to that file). VSCode seems to initially recognize that all the functions being used in the playscene0 function have been successfully imported.
In my importtest file:
from scenes.scene0 import playscene0
playscene0()
This gives me:
NameError: name 'print_italics' is not defined
Though it very much is defined in the file it is derived from.
I've already looked into circular imports and how they cause problems, but that doesn't seem to be the cause here. I've tried importing both time and everything from scenetext.textstuff in the importtest file directly, but the problem persists.
Any suggestions are welcome, thank you
EDIT: After adding from scenetext.textstuff import print_italics to the importtest file, it gives me a different error upon running:
ImportError: cannot import name 'print_italics' from 'scenetext.textstuff' (/Users/[me]/vscode/VOYAGE/scenetext/textstuff.py)
Not sure what causes this.
You need to add an import to the importtest file - from scenetext.textstuff import print_italics, so that the function becomes "visible".
You should import the textstuff functions BEFORE you import the playscene function that uses them
from scenetect.textstuff import print_italics
from scenes.scene0 import playscene0
playscene0()

Incorporating one code into another

I have an existing python script which contains a function ('function_1') and some other lines of code that execute function_1 at some point. Lets call this script 'code_a.py'.
I now have another larger script ('code_b.py'). Within this script, I want code_a.py to run in its entirety.
I'm trying to learn what the best way to do this would be.
Obviously, I could just copy and paste the whole of code_a.py into the body of code_b.py - which seems like a terrible way of doing things.
So I was thinking that at the beginning of code_b.py, I could do something like:
import code_a
But as I understand it, that would only import function_1 from code_a. So should I re-write the whole of code_a as a big function, so that it can be imported into code_b?
Or am I thinking about this is the wrong way?
Thanks.
If i understand your problem correctly, you dont want to import function_1 from code_a, you actually want to execute the whole code.
One thing you can do is use the os module in python to execute a shell/cmd command from within code_b.py like so:
import os
os.system('python code_a.py')

Add a module when running a python program from terminal

I wrote a module that, if it is imported, automatically changes the error output of my program. It is quite handy to have it in almost any python code I write.
Thus I don't want to add the line import my_errorhook to every code I write but want to have this line added automatically.
I found this answer, stating that it should be avoided to change the behavior of python directly. So I thought about changing the command line, something like
python --importModule my_errorhook main.py
and defining an alias in the bashrc to overwrite the python command to automatically add the parameter. Is there any way I could achieve such a behavior?
There is no such thing like --importModule in python command line. The only way you can incept the code without explicitly importing is by putting your functions in builtins module. However, this is a practice that is discouraged because it makes your code hard to maintain without proper design.
Let's assume that your python file main.py is the entry point of the whole program. Now you can create another file bootstrap.py, and put below codes into the new file.
import main
__builtins__.func = lambda x: x>=0
main.main()
Then the function func() can be called from all modules without being imported. For example in main.py
def main():
...
print(func(1))
...

Is it possible to run imported code as a part of the main file?

The question is pretty simple: I need to move a piece of my code to the another file. In the main file, I'll do something like import not_main. Is is possible to run imported code as a part of the main file? Here's a simplified example:
__code
\__main.py
|__not_main.py
main.py content:
a = 5
import not_main
not_main.py content:
print a
When I'm running main.py, there is a error : NameError: name 'a' is not defined. How can I make it work? Thanks for any tips.
It's not possible to directly reference a variable in one module that's defined in another module unless you import that module first. Doesn't matter that it's the main module, this error would happen if you tried to do the same between any two modules. An imported module does not gain the scope of the module it's imported into.
There are possible workarounds, though I would caution using them if the code you're trying to separate out is fairly complex. But if you're intent on doing it, I'd suggest separating out any variables needed in both modules into a third module that only contains those variables. So the simple example you gave would turn into this:
cross_module_variables.py:
a = 5
main.py:
import not_main
not_main.py:
import cross_module_variables as cmv
print cmv.a
For more complex code you might need to assign the value of the variable in main after doing executing some code to produce the value. In that case you'll want to import cross_module_variables into the main module and assign a value to it. Course that variable has to be instantiated before it can be used in main so you'll have define the variable in cross_module_variable with some default value. So it would look something more like this:
cross_module_variables.py:
a = 0
main.py:
import cross_module_variables as cmv
cmv.a = 5
import not_main
not_main.py:
import cross_module_variables as cmv
print cmv.a
See this answer for more info on cross module variables.
With all that said, I would highly suggest you look at restructuring your code in some other sane way. It sounds like you're running all your code straight in modules instead of defining functions around discrete sections of code. You should look into ways of designing coherent functional programs.

how to execute nested python files

I have 3 python files.(first.py, second.py, third.py) I'm executing 2nd python file from the 1st python file. 2nd python file uses the 'import' statement to make use of 3rd python file. This is what I'm doing.
This is my code.
first.py
import os
file_path = "folder\second.py"
os.system(file_path)
second.py
import third
...
(rest of the code)
third.py (which contains ReportLab code for generating PDF )
....
canvas.drawImage('xyz.jpg',0.2*inch, 7.65*inch, width=w*scale, height=h*scale)
....
when I'm executing this code, it gives error
IOError: Cannot open resource "xyz.jpg"
But when i execute second.py file directly by writing python second.py , everything works fine..!!
Even i tried this code,
file_path = "folder\second.py"
execfile(file_path)
But it gives this error,
ImportError: No module named third
But as i stated everything works fine if i directly execute the second.py file. !!
why this is happening? Is there any better idea for executing such a kind of nested python files?
Any idea or suggestions would be greatly appreciated.
I used this three files just to give the basic idea of my structure. You can consider this flow of execution as a single process. There are too many processes like this and each file contains thousandth lines of codes. That's why i can't change the whole code to be modularize which can be used by import statement. :-(
So the question is how to make a single python file which will take care of executing all the other processes. (If we are executing each process individually, everything works fine )
This should be easy if you do it the right way. There's a couple steps that you can follow to set it up.
Step 1: Set your files up to be run or imported
#!/usr/bin/env python
def main():
do_stuff()
if __name__ == '__main__':
The __name__ special variable will contain __main__ when invoked as a script, and the module name if imported. You can use that to provide a file that can be used either way.
Step 2: Make your subdirectory a package
If you add an empty file called __init__.py to folder, it becomes a package that you can import.
Step 3: Import and run your scripts
from folder import first, second, third
first.main()
second.main()
third.main()
The way you are doing thing is invalid.
You should: create a main application, and import 1,2,3.
In 1,2,3: You should define the things as your functions. Then call them from the main application.
IMHO: I don't need that you have much code to put into separate files, you just also put them into one file with function definitions and call them properly.
I second S.Lott: You really should rethink your design.
But just to provide an answer to your specific problem:
From what I can guess so far, you have second.py and third.py in folder, along with xyz.jpg. To make this work, you will have to change your working directory first. Try it in this way in first.py:
import os
....
os.chdir('folder')
execfile('second.py')
Try reading about the os module.
Future readers:
Pradyumna's answer from here solved Moin Ahmed's second issue for me:
import sys, change "sys.path" by appending the path during run
time,then import the module that will help
[i.e. sys.path.append(execfile's directory)]

Categories