i have a test script test.py inside which i am trying to run one more python script bexec.app(this is a python script). Actually test.py is just for my testing. The original script is a lengthy one and bexec.app is getting called inside in a command line.
I tried this
#!/usr/bin/python
import os, sys
os.path.insert(0, 'current bexec script path')
import bexec.app
But this does not work -
Traceback (most recent call last):
File "test", line 5, in <module>
import bexec.pphshaper
ImportError: No module named bexec.app
I donot want to change the bexec.app script to bexec_app.py because this follows some naming convention
bexec.app also has #!/usr/bin/python inside it.
how can i import my bexec script inside test.py
You seem to want to run your bexec, not import it. And if so, regular
os.system('current bexec script path')
should be sufficient
Dot means subpackage structure to python, but it's still possible with imp.
below is bexec.app sample file:
#!/usr/bin/python
a = 2
and this is how you can import it in your test.py file, look below for the code:
#!/usr/bin/python
import os, sys, imp
my_module = imp.load_source('my_module', 'bexec.app')
print (my_module.a)
Related
When I try importing functions and classes that I've created in Python scripts into a Jupyter Notebook, I get import errors. However, when I run the same code in a regular script rather than in a notebook, it runs without a problem.
All three files are in the same directory:
First, I have my_function_script.py, which defines functions.
def my_function():
pass
Second, I have my_class_script, which both imports the functions defines classes:
from my_function_script import my_function
class my_class():
pass
When I try to run the below import script in a Jupyter Notebook, I get an ImportError.
from my_class_script import my_class
ImportError Traceback (most recent call last)
<ipython-input-6-8f2c4c886b44> in <module>
----> 1 from my_class_script import my_class
~\my_directory\my_class_script.py in <module>
5
----> 6 from my_function_script import my_function
ImportError: cannot import name 'my_function' from 'my_function_script' (C:\Users\my_directory\my_function_script.py)
I believe that the problem is specific to the Jupyter Notebook for two reasons. First, I've confirmed that both my_function_script.py and my_class_script.py can run in the terminal without error. Second, when I take the same line that causes the Jupyter Notebook to error and run it in a regular Python script, it runs without error.
I have Windows, and I don't have multiple environments or versions of Python.
you can add to the Python path at runtime:
# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '/path/to/application/app/folder')
import file
this usually happens when your jupyter notebook does not point to the correct directory for importing
one way to fix this would be to change the working directory in jupyter notebook
import os
os.chdir('path/to/python/scripts/directory')
from my_class_script import my_class
another way to do this is using UNIX commands directly in jupyter notebook
cd /path/to/python_script_directory
from my_class_script import my_class
make sure you dont put the cd command and import statement in the same notebook block
I'm running my Python script in Terminal on MacOS.
The script1.py source code:
# A first Python script
import sys # Load a library module
print(sys.platform)
print(2 ** 100) # Raise 2 to a power
x = 'Spam!'
print(x * 8) # String repetition
The output in the Python interactive session:
>>> import script1.py
darwin
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'script1.py'; 'script1' is not a package
All the statements in the script are executed correctly, but the interpreter returns an error that says the script can't be found.
What's going on here?
import script1.py
The interpreter is thinking you're trying to import the module named py from inside the package script1.
Now, it can find a file called script1 - that's your file called script1.py. So it goes ahead and loads it. And "loading" for python means running the statements inside the file. So it does that. And you get your output.
Then the interpreter realizes that it was expecting py to be a module, so script1 should've been a package (i.e. a directory with source files inside it). But script1 was just an ordinary file. Hence it throws that error.
When trying to import a module named script1.py, you should use:
import script1
When trying to run a file called script1.py, you may use:
python script.py
You should delete the .py at the end. When you import sys you also dont write import sys.py. See also this post answering how to import your own scripts in python.
I have a main script that import the module from another script (sub_script.py) using importlib. I also pass the argument to the other script:
import importlib
parser = argparse.ArgumentParser(add_help=False)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-option1', action = "store_true")
args = parser.parse_known_args()
if args[0].option1:
function = importlib.import_module('sub_script')
function.main(namespace = args[1])
While this code runs fine by itself (using Python main_script.py), it returns the following error message after I complied it with Pyinstaller:
Traceback (most recent call last):
File "<string>", line 33, in <module>
ImportError: No module named sub_script
main_script returned -1
I tried to:
1) add a __init__.py under my folder
or
2) move sub_script.py to a sub_folder with __init__.py
but either works.
I also tried to complied it under Ubuntu, but got the same message.
However, it complied and ran fine if I just using import:
import sub_script
Any ideas? Thanks!
pyinstaller can't automatically package a module that is imported dynamically. If you really need to use importlib to import the module, then you need to tell pyinstaller. You can use the --hidden-import option for this:
--hidden-import MODULENAME, --hiddenimport MODULENAME
Name an import not visible in the code of the script(s). This option can be used multiple times.
See PyInstaller Docs for more detail
I have this line of import in my python code:
from project.lib.framework.test_cases import TestCase
and it works fine when I run it from command line. However, if I try to run it from my IDE (Active state komodo), I get an error:
ImportError: No module named project.lib.framework.test_case.
Can anyone tell me why?
Because you changed the import statement?
In the first example, you are importing from project.lib.framework.test_cases, but in the second, you appear to be importing from project.lib.framework.test_case. Notice the missing s at the end.
Other then that, assuming you are using the same python binary, there should be no difference between an IDE and a command line for import statements.
I noticed the following using Python 2.5.2 (does not occur using 2.7):
#!/usr/bin/python
import sys
for line in sys.stdin:
print line,
Output:
$ echo -e "one\ntwo\nthree" | python test.py
$ one
$ two
$ three
as expected. However, if I import subprocess to the this script:
#!/usr/bin/python
import sys
import subprocess
for line in sys.stdin:
print line,
Output:
$ echo -e "one\ntwo\nthree" | python test.py
$ two
$ three
What happened to the first line of output?
Update:
I think I may have discovered the root of the problem. I had a file named time.py in my cwd. A time.pyc is being created every time I run the script with subprocess imported, suggesting that ./time.py is also being imported. The script runs normally if I delete the .pyc and time.py files; however, there is still the question of why a subprocess import would cause ./time.py to be imported as well?
I have narrowed it down even further to the exact line in time.py that causes the strange behaviour. I have stripped down the working dir and file content to just that which affects the output:
test.py
#!/usr/bin/python
import sys
import subprocess
for line in sys.stdin:
print line,
time.py
#!/usr/bin/python
import sys
for line in sys.stdin:
hour = re.search(r'\b([0-9]{2}):', line).group(1)
Running test.py with any kind of input results in the first line of output being omitted and time.pyc being created.
Sounds like your local time.py will be imported instead of the global time module. You might want to rename it, or at least start checking if it was run as a script or imported as a module.
This will prove it for you if you want to test it.
#!/usr/bin/python
import sys
# Test that script was run directly
if __name__=='__main__':
for line in sys.stdin:
hour = re.search(r'\b([0-9]{2}):', line).group(1)
else:
print 'Imported local time.py instead of global time module!'
sys.exit(1)
print line, before 2.7 did not put out a newline so it overwrote the first line. Lose the comma and the result will be the same.