File ex.py:
print('hello,word')
Trial run:
>>> d:\learning\python\ex.py
SyntaxError: invalid syntax
On the command line, outside the Python console, type:
python D:\learning\python\ex.py
You need to import the module:
>>> import ex
See the documentation about modules
The module has to be on your path or in the current working directory. You can change directories using chdir:
>>> import os
>>> os.chdir(r'd:\learning\python')
>>> import ex
hello,word
Or, in the command prompt, you can set PYTHONPATH=d:\learning\python, for example, before you start python, and d:\learning\python will get added to sys.path.
Instead, you could add it programatically:
>>> import sys
>>> sys.path.insert(0, r'd:\learning\python')
>>> import ex
hello,word
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 have fetched files from windows shared drive having path as follows:
\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls
I want to fetch filename from this path which is futurefilesomf.egus.xls
when I tried as file_path.split('\') . It's giving error as SyntaxError: EOL while scanning string literal
I can't do file_path.split('\\') because then it will give me None.
Even if I do file_path.replace('\\','\'), still same error.
What could be the solution.
Marked as 3.x so I'll assume you have 3.4+ available for Pathlib
import pathlib
path = r"\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls"
print(pathlib.Path(path).name)
print(pathlib.Path(path).name == "futurefilesomf.egus.xls")
Use basename instead of splitting:
>>> s = r"\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls"
>>> import os
>>> os.path.basename(s)
'futurefilesomf.egus.xls'
You can use ntpath:
full_path = r'\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls'
import ntpath
ntpath.split(full_path)
which gives:
('\\\\piyush123\\piyushtech$\\Piyush\\ProFileTesting\\May\\Input_File\\OMF', 'futurefilesomf.egus.xls')
You can do file_path.split('\\'). Do it like this:
>>> file_path=r"\\piyush123\piyushtech$\Piyush\ProFileTesting\May\Input_File\OMF\futurefilesomf.egus.xls"
>>> file_path.split('\\')
['', '', 'piyush123', 'piyushtech$', 'Piyush', 'ProFileTesting', 'May', 'Input_File', 'OMF', 'futurefilesomf.egus.xls']
Though you problably really need to combine it with a function from the os.path family, for example:
>>> os.path.splitunc(file_path)
('\\\\piyush123\\piyushtech$', '\\Piyush\\ProFileTesting\\May\\Input_File\\OMF\\futurefilesomf.egus.xls')
I have the following python structure
directory structure
In login_logout_test.py I use the following imports and everything works fine when I run this script (all the modules are imported properly)
import sys, os
parentPath = os.path.abspath("..")
if parentPath not in sys.path:
sys.path.insert(0, parentPath)
import common_test_functions as cts
from functions import login_logout_functions as llf
But when this script (login_logout_test.py) is called by CommandRunner.py this error occurs:
No module named 'common_test_functions'
Actually I have contrived a solution to my own problem:
import sys, os
from selenium import webdriver
# adding path to common_test_functions to the sys.path
# so this module could be invoked
parentPath = os.path.abspath("..\\..")
if parentPath not in sys.path:
sys.path.append(parentPath)
from functions import login_logout_functions as llf
from tests import common_test_functions as cts
Also there is a file, that holds necessary for the script parameters. Here is the code to have this file path in both cases (running this script by itself or calling it by another script):
parameters_directory_path = os.path.dirname(os.path.realpath(__file__))
parameters_file_name = "login_logout_test_parameters.tsv"
parameters_file_path = os.path.join(parameters_file_path, parameters_file_name)
If someone has a better one, please post it.
Thank you in advance.
Stefan
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
I recently installed a library in Python 3.3.2. I tried to import a module from it like this: import cx_Freeze.freezer. However, cx_Freeze.freezer is not defined as I would have expected, as shown in IDLE:
>>> ================================ RESTART ================================
>>> import cx_Freeze.freezer
>>> cx_Freeze.freezer
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
cx_Freeze.freezer
AttributeError: 'module' object has no attribute 'freezer'
>>>
The same thing happens in the command line. I think I am misunderstanding what happens when you use import with dot notation; what name does the module get assigned to?
In order to fix this seeming problem, I tried import cx_Freeze.freezer as f after restarting the shell, but that gave the same error as before. Can someone please explain why these import statements aren't giving me access to the module?
cx_Freeze/__init__.py has the following contents:
version = "5.0"
import sys
from cx_Freeze.dist import *
if sys.platform == "win32":
from cx_Freeze.windist import *
elif sys.platform == "darwin":
from cx_Freeze.macdist import *
from cx_Freeze.finder import *
from cx_Freeze.freezer import *
from cx_Freeze.main import *
del dist
del finder
del freezer
The parts important to this question are from cx_Freeze.freezer import * and del freezer. The first of those lines imports everything listed in cx_Freeze.freezer.__all__ directly into the cx_Freeze package, and the second line makes cx_Freeze.freezer not available directly. Thus, you should probably just use cx_Freeze; it contains all the parts of cx_Freeze.freezer designed for external use. If you need cx_Freeze.freezer, perhaps to use some of the private functionality, you can find it in sys.modules:
import sys
freezer = sys.modules['cx_Freeze.freezer']