Python "module 'fileName' has no attribute 'functionName'" - python

I have a main.py file accessing a number of other modules.
I want to call the function using fileName.fileFunction()
In the module I want to access, I am importing the main.py file and the code is as follows:
import main
def fileFunction():
statements
statements
var = input("enter a name")
statements
return var
I want to access the value the user enters into var and then use that in my main module but I get the following error:
module 'fileName' has no attribute 'fileFunction'

I think you've got it backwards.
fileName.py
#!/usr/bin/python
def fileFunction():
var = print("enter a name")
return var
main.py
#!/usr/bin/python
import fileName
fileName.fileFunction()
command:
$ python main.py
enter a name

you try to do like this ?
file_name.py
def file_function():
retunrn 'file_name'
main.py
from file_name import file_function
your_file.py
import main
print(main.file_function())

In your main file you called fileName.fileFunction()
and in your fileName you imported main.
While executing the fileName module your main file will execute first in which you have fileFunction() which is not defined.
import the fileName module in your main and remove import main line from the fileName module.
Main.py
import fileName
print(fileName.fileFunction())
fileName.py
def fileFunction():
a=input("Enter a name : ")
return a

Related

How do I open another Python file within a file with a parameter/argument/variable attached?

I want to run another file from my main.py and also set the value of a variable in the main.py and "export it", so I can use it in the other file.
But I absolutely don´t know how to do that.
So that I can set a 'var = x[3]' in the main file and kinda "export" the variable into the file that I am opening like 'import otherfile.py(var = x[3])'
Thanks in advance
To import any variable from main file to otherfile you can use,
from main import*
Y = var
That's how you can set var in main.py file and import or use it in otherfile.py.
You can use sys.argv to get arguments if you run the file from the command line
so if you have the file:
import sys
print(sys.argv[0])
then open a command line and type python file.py hello it will print 'hello'.
As well, you can use os.system() to run command line functions from python
so your first file could be:
import os
var = 'test'
os.system(f"python otherfile.py {var}")
and otherfile.py could be:
import sys
print(sys.argv[0])
then if you run the first file, a python window will open and print 'test'.
Hope this was what you were looking for

Python ModuleNotFoundError when trying to run main.py

I am pretty new to python and have been working on a data validation program. I am trying to run my main.py file but I am getting the following error.
Traceback (most recent call last):
File "/Users/user/data_validation/main.py", line 5, in <module>
from src.compile_csv import combine_csv_files
File "/Users/user/data_validation/src/compile_csv.py", line 5, in <module>
from helpers.helper_methods import set_home_path
ModuleNotFoundError: No module named 'helpers'
I am using python version 3.94
This is my folder structure
data_validation
- src
- files
validation.csv
- folder_one
combined.csv
- folder_two
combined_two.csv
- helpers
helper_methods.py
compile_csv.py
mysql.py
split.py
main.py
Both compile_csv.py and split.py use methods from helpers.helper_methods.py
My main.py which is throwing the error when being run, looks like the following:
import os
import sys
import earthpy as et
from src.mysql import insert_data, output_non_matches
from src.compile_csv import combine_csv_files
from src.split import final_merged_file
from src.helpers.helper_methods import set_home_path, does_file_exist
home_path = et.io.HOME
file_path = home_path, "data_validation", "src", "files"
folder_name = sys.argv[1]
def configure_file_path():
master_aims_file = os.path.join(
file_path, "validation.csv")
output_csv = os.path.join(
file_path, "output.csv.csv")
gdpr_file_csv = set_home_path(folder_name + "_output.csv")
output_csv = does_file_exist(os.path.join(
file_path, folder_name + "_mismatch_output.csv"))
return output_csv, master_aims_file, gdpr_file_csv
output_csv, master_aims_file, gdpr_file_csv = configure_file_path()
if __name__ == "__main__":
print("🏁 Finding names which do not match name in master file")
if (folder_name == "pd") and (folder_name == "wu"):
final_merged_file()
else:
combine_csv_files()
insert_failures = insert_data(output_csv, master_aims_file)
output_failures = output_non_matches(output_csv, gdpr_file_csv)
if insert_failures or output_failures:
exit(
"⚠️ There were errors in finding non-matching data, read above for more info"
)
os.remove(os.path.join(home_path, "data_validation", "members_data.db"))
exit(
f"✅ mismatches found and have been outputted to {output_csv} in the {folder_name} folder")
From what I understand in python 3 we do not need to use __init__.py and you can use . for defining the path during import, So I am not entirely sure as to what I am doing wrong.
I am executing the file from /Users/user/data_validation and using the following command python main.py pd
There it is. The error is happening in your compile_csv.py file. I'm guessing in that file you have from helpers.helper_methods import blah. But you need to change it to
from .helpers.helper_methods import blah
OR
from src.helpers.helper_methods import blah
Reason being is that imports are relative to cwd not to the file where the code is running. So you need to add the import relative to /Users/user/data_validation.
you can try by setting PYTHONPATH variable. check more about it here

How to give path for file passed through command line

I got answer for how to pass file as argument here How to access variables from file passed through command line
But I am asking separately since don't wanna mix two.
I am able to access variables in passed file as __import__(sys.argv[1]) and called python test.py config. But can I call config.py file by giving pythonpath? e/g/ python test.py ~/Desktop/config or PYTHONPATH='~/Desktop/' python test.py config? Because if I do this I get no module error.
You're trying to import a python module using the __import__ call. It only accepts the module name. If you need to add a directory to the PYTHONPATH, you can add it to sys.path and then import the module:
#File: ~/Projects/py/main.py
import sys
python_path = sys.argv[1]
module_name = sys.argv[2]
sys.path.insert(1, python_path)
print "Importing {} from {}".format(module_name, python_path)
__import__(module_name)
Now I created another file named masnun.py on ~/Desktop:
# File: ~/Desktop/masnun.py
print "Thanks for importing masnun.py"
Now I try to run main.py like this:
python main.py ~/Desktop masnun
So I am passing the Python path as argv[1] and the module name as argv[2]. Now it works. I get this output:

From *folder_name* import *variable* Python 3.4.2

File setup:
...\Project_Folder
...\Project_Folder\Project.py
...\Project_folder\Script\TestScript.py
I'm attempting to have Project.py import modules from the folder Script based on user input.
Python Version: 3.4.2
Ideally, the script would look something like
q = str(input("Input: "))
from Script import q
However, python does not recognize q as a variable when using import.
I've tried using importlib, however I cannot figure out how to import from the Script folder mentioned above.
import importlib
q = str(input("Input: "))
module = importlib.import_module(q, package=None)
I'm not certain where I would implement the file path.
Repeat of my answer originally posted at How to import a module given the full path?
as this is a Python 3.4 specific question:
This area of Python 3.4 seems to be extremely tortuous to understand, mainly because the documentation doesn't give good examples! This was my attempt using non-deprecated modules. It will import a module given the path to the .py file. I'm using it to load "plugins" at runtime.
def import_module_from_file(full_path_to_module):
"""
Import a module given the full path/filename of the .py file
Python 3.4
"""
module = None
try:
# Get module name and path from full path
module_dir, module_file = os.path.split(full_path_to_module)
module_name, module_ext = os.path.splitext(module_file)
# Get module "spec" from filename
spec = importlib.util.spec_from_file_location(module_name,full_path_to_module)
module = spec.loader.load_module()
except Exception as ec:
# Simple error printing
# Insert "sophisticated" stuff here
print(ec)
finally:
return module
# load module dynamically
path = "<enter your path here>"
module = import_module_from_file(path)
# Now use the module
# e.g. module.myFunction()
I did this by defining the entire import line as a string, formatting the string with q and then using the exec command:
imp = 'from Script import %s' %q
exec imp

How to import a function which is in a different directory

I am trying to calling a function from a module which is located in different directory than the current.
This is code I am using
c:\commands contains a file nlog.py which contains function parselog . i would like to importing this function
into a python file in other directory c:\applications
def parselog(inFileDir = )
### This is in directory c:\commands which need to imported ####
c:\applications\pscan.py is the script which is calling / importing from the above file / directory
if __name__ == '__main__':
#sys.path.append("C:/commands")
sys.path.insert(0,'C:/commands')
from commands import nlog
def pscan (infileDir = )
parselog(inFileDir=r'os.getcwd()') # I am calling the function here
We are getting error
NameError: global name 'parselog' is not defined
I am not sure if I am importing in a wrong way. The C:\commands folder contains _init_.py file. Please let me know what I am missing.
Make and empty __init__.py file in the folder of the module you want to import.
Below code should work.
import sys
sys.path.append(r'c:\commands')
import nlog
parselog(inFileDir=r'os.getcwd()')

Categories