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:
Related
I am running python code in docker.
I have the following file structure:
-my_dir
-test.py
-bird.py
-string_int_label_map_pb2.py
-inference.py
inference.py:
import test
import bird
from string_int_label_map_pb2 import StringIntLabelMap
test.py and bird.py both contain this code:
print('hello world!')
def this_is_test():
return 'hi'
In inference.py 'import test' throws no error(but 'hello world!' is never printed).
'import bird' throws: ModuleNotFoundError: No module named 'bird'. Finally
'import string_int_label_map_pb2 ' throws: ModuleNotFoundError: No module named 'string_int_label_map_pb2 '
Note: bird.py and test.py are not simultaneously existing in the dir, they are depticted as such only to make my point. They exist only when I rename the same file to either name to test if the name itself was to blame.
If one or the other is not in the folder but you still have import test and import bird in the inference.py, that's your issue. Python is trying to import both files but can not find the file.
I added bird.py to /worker/ (the WORKDIR path configured in the dockerfile) and sure enough "Hello world!" printed.
So the issue was that inference.py was not searching its parent dir for imports as I thought, but rather the path configured in WORKDIR.
Still don't understand why import test gave no errors since there was never a test.py file in /worker/.
I also had this problem, how did I solve the problem?
For example.
My directory:
--Application
---hooks
----init.py
----helpers.py
---model
----init.py
----model_person.py
In script model_person.py
import sys
sys.path.append('../')
from hooks.helpers import *
Thats all
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
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
I'm trying to use a variable as a module to import from in Python.
Using ImportLib I have been successfully able to find the test...
sys.path.insert(0, sys.path[0] + '\\tests')
tool_name = selected_tool.split(".")[0]
selected_module = importlib.import_module("script1")
print(selected_module)
... and by printing the select_module I can see that it succesfully finds the script:
<module 'script1' from 'C:\\Users\\.....">
However, when I try to use this variable in the code to import a module from it:
from selected_module import run
run(1337)
The program quits with the following error:
ImportError: No module named 'selected_module'
I have tried to add a init.py file to the main directory and the /test directory where the scripts are, but to no avail. I'm sure it's just something stupidly small I'm missing - does anyone know?
Import statements are not sensitive to variables! Their content are treated as literals
An example:
urllib = "foo"
from urllib import parse # loads "urllib.parse", not "foo.parse"
print(parse)
Note that from my_module import my_func will simply bind my_module.my_func to the local name my_func. If you have already imported the module via importlib.import_module, you can just do this yourself:
# ... your code here
run = selected_module.run # bind module function to local name
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