I can't use the module I created in my main python file - module

I created a module named module_1:
def learn(programming_lang):
print("I am learning " + programming_lang)
and I want to use it in my main Python file.
module_1.learn("Python")
How can I do that?

in main Python file add this line
import module_1

Related

Using import lib to change which module I want to import

I have a directory and inside of the directory are subdirectories and a python file trying to run other files called Main.py. In each of the subdirectories there will be one file called runner.py with its only function I need to execute is “func”. If I want to use importlib.importmodule how would I go about doing that. As of right now I’m iterating over the directory and using:
filepath = sys.argv\[1\] + "/runner.py"
student_module = importlib.import_module("func", filepath)
But I’m afraid I don’t know how to use it properly as I’m new to python.
In case my words weren’t clear the directory architecture is as follows
Directory
->Main.py
->Subdirectory(1)
->runner.py
->Subdirectory(2)
->runner.py
.
.
.
->Subdirectory(n)
->runner.py
I had tried using the snippet of code above and I was expecting to be able to run the func from the different runner.py files. Unfortunately I’m getting a:
ModuleNotFoundError: No module named ‘func’

Generate data file at install time

My python package depends on a static data file which is automatically generated from a smaller seed file using a function that is part of the package.
It makes sense to me to do this generation at the time of running setup.py install, is there a standard way in setup() to describe “run this function before installing this package's additional files” (the options in the docs are all static)? If not, where should I place the call to that function?
Best done in two steps using the cmdclass mechanism:
add a custom command to generate the data file
override build_py to call that before proceeding
from distutils.cmd import Command
from setuptools import setup
from setuptools.command.install import install
class GenerateDataFileCommand(Command):
description = 'generate data file'
user_options = []
def run(self):
pass # Do something here...
class InstallCommand(install):
def run(self):
self.run_command('generate_data_file')
return super().run()
setup(
cmdclass={
'generate_data_file': GenerateDataFileCommand,
'install': InstallCommand,
},
# ...
)
This way you can call python setup.py generate_data_file to generate the data file as a stand-alone step, but the usual setup procedure (python setup.py install) will also ensure it's called.
(However, I'd recommend including the built file in the distribution archive, so end users don't have to build it themselves – that is, override build_py (class setuptools.command.build_py.build_py) instead of install.)

Preventing overwriting when using numpy.savetxt

Is there built error handling for prevent overwriting a file when using numpy.savetxt?
If 'my_file' already exists, and I run
numpy.savetxt("my_file", my_array)
I want an error to be generated telling me the file already exists, or asking if the user is sure they want to write to the file.
You can check if the file already exists before you write your data:
import os
if not os.path.exists('my_file'): numpy.savetxt('my_file', my_array)
You can pass instead of a filename a file handle to np.savetxt(), e.g.,
import numpy as np
a = np.random.rand(10)
with open("/tmp/tst.txt", 'w') as f:
np.savetxt(f,a)
So you could write a helper for opening the file.
Not in Numpy. I suggest writing to a namedTemporaryFile and checking if the destination file exists. If not, rename the file to a concrete file on the system. Else, raise an error.
Not an error handler, but it's possible to create a new version in the form of:
file
filev2
filev2v3
filev2v3v4
so that no file ever gets overwritten.
n=2
while os.path.exists(f'{file}.txt'):
file = file + f'v{n}'
n+=1

ImportError: No module named texttable (igraph, py2exe,cx freeze/gui2exe)

I've spent 2 days trying to solve this problem and I'm getting nowhere.
I try to get an executable from my python script.
Script is running with no issues. I build graphs in it by using igraph which is my favorite choice for this task.
After compiling my script I get the results as expected (Dist folder with my exe and its stuff in it)
When I try to run the exe I get this annoying error message:
File "igraph\__init__.pyc", line 36, in <module>
File "igraph\clustering.pyc", line 38, in <module>
File "igraph\summary.pyc", line 36, in <module>
File "igraph\vendor\__init__.pyc", line 33, in vendor_import
ImportError: No module named texttable
I checked many threads related to ImportError. I went in the folder containing texttable and IT'S THERE! It's not missing! I've tryed something with changing the path but still no succes.
at the beginning of my script I have:
import re
import os
import csv
import math
from igraph import *
import thread
import unicodedata
from time import sleep
import wx.grid as gridlib
import sys
import Tkinter
from Tkinter import *
I have tryed from igraph import Graph but it would still look for that TEXTTABLE.
I've tried using py2exe, cx freeze and also the nice Gui interface to them GUI2exe. No luck. Same Error whatever I try.
I'm sorry if the solution is obvious. I'm not a pro. Any help is much appreciated!
igraph is importing texttable dynamically, so the freezing tools don't know that they need to copy the module in.
In cx_Freeze, you could add igraph.vendor to 'packages' (see the docs) to force it to copy everything from that package. There's probably a similar option for py2exe.
Alternatively, if you put import igraph.vendor.texttable somewhere in the code, the freezing tools will pick that up and know to include it.

Modify instance variables from another file?

It is possible to modify an instance variable from another file?
What I want is to modify an instance variable inside File_1 from File_2.
For example:
//File 1
import File_2
class Main:
def __init__(self):
self.example = "Unmodified"
def modify(self):
File_2.modify()
main = Main()
main.modify()
//File 2
import File_1
def modify():
File_1.main.example = "Modified"
This gives me the following output:
Traceback (most recent call last):
File "File_1.py", line 4, in <module>
import File_2
File "File_2.py", line 3, in <module>
import File_1
File "File_1.py", line 14, in <module>
main.modify()
File "File_1.py", line 11, in modify
File_2.modify()
AttributeError: 'module' object has no attribute 'modify'
Why?
EDIT (to explain better):
The instance of the main class (in file 1) has a variable; what I want is to modify that variable from another file (file 2). I modified a little bit the code:
//File 1
import File_2
class Main:
def __init__(self):
self.example = "Unmodified"
def modify(self):
File_2.modify()
if __name__ == "__main__":
main = Main()
main.modify()
//File 2
def modify():
//do some stuff
//now I want to modify the example variable from the main class, but how?
Your code is full of cyclic imports, take a look at Python: Circular (or cyclic) imports to know what I'm talking about.
Basically the problem is that when the compiler comes to this line:
File_2.modify()
File_2 is not completely loaded, menaning that the compiler have not yet read the lines:
def modify():
File_1.main.example = "Modified"
Since it was brought back to File_1 from the previous:
import File_1
Besides this, you're code seems quite strange. If you care to provide more information about your real code, maybe a better design could solve your problem.
Edit: You have to remove the cyclic imports. One way to do what you seem to need is to pass an argument to the File_2.modify(arg) function, and work on that:
# File_2
# !! do NOT import File_1 in this file
def modify(obj):
obj.value += 7
But in your case you'll have to pass the whole object (self) to the modify function, and is some of a waste to modify only one value.
It would be better to do something like:
# File_1
import File_2
class Main:
# ...
def modify()
self.value = File_2.modify(self.value)
# File_2
# !! do NOT import File_1 in this file
def modify(num):
return num + 7
But once again this are just examples, since your not showing your real code, we can't really tell you what's best in your case (maybe neither of the above) or help you very much.
What does not work in Python is this "cross importing" you are trying to do -
When you do both files import each other, you have inconsistencies and undesireable side effects. In this case when the main.modify() line is run at File_1 parsing, it does find a not yet fully initialized "File_2" module in memory - where the "modify" function does not exist yet.
Reorder yoru code so you don't have the cyclic imports, and it should work -
For example, if teh file you import first - or run as main module, is File_1, inside File_2, instead of import File_2 in the first line, import it just inside the modify function, like this:
#File 2
def modify():
import File_1
File_1.main.example = "Modified"
N.B. these imports, since they are referencing a module that isa ctually already imported on the interpreter, just bind the module object, already loaded, to the variable in the running scope - in other words, Python won't do a disk access for the module file at each time the function is called.