os.path.dirname(__file__) not displaying absolute path in python 2.7 - python-2.7

I just have a python file:
#!/usr/bin/python
import os
print os.path.dirname(__file__)
but when I execute it, the terminal displays a dot, instead of the absolute path to the script.

Perhaps,
#!/usr/bin/python
import os
print os.path.realpath(__file__)
gives you what you're looking for?

Related

Calling "which program" from Python with os.system or subprocess doesn't return path

I'm using Python Version 2.7.10 with macOS Sierra 10.12.16 and Xcode 8.3.3.
I want to call latex from Python. os.system('latex myFile.tex') does not work because the complete path is needed. So I tried to get the path with the which program command.
import os
import subprocess
batcmd = '/usr/bin/which latex'
thePath = os.system(batcmd)
print("The path: "+str(thePath))
p = subprocess.Popen([batcmd], stdout=subprocess.PIPE, shell=True)
print(p.stdout.read())
The results I get from both variations are:
he path: 256
Program end
with exit code: 0
The system command delivers the number 256. The subprocess command derives an empty line. Other system calls like ls or dir work fine.
How can I get the path of a program with Python?
The path var is included in my custom bin dirs, including Latex.
import os
os.environ["PATH"] += os.pathsep + '/usr/local/.......'
print(os.getenv("PATH"))

Shebang command to call script from existing script - Python

I am running a python script on my raspberry pi, at the end of which I want to call a second python script in the same directory. I call it using the os.system() command as shown in the code snippet below but get import errors. I understand this is because the system interprets the script name as a shell command and needs to be told to run it using python, using the shebang line at the beginning of my second script.
#!/usr/bin/env python
However doing so does not solve the errors
Here is the ending snippet from the first script:
# Time to Predict E
end3 = time.time()
prediction_time = end3-start3
print ("\nPrediction time: ", prediction_time, "seconds")
i = i+1
print (i)
script = '/home/pi/piNN/exampleScript.py'
os.system('"' + script + '"')
and here is the beginning of my second script:
'#!usr/bin/env python'
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from picamera import PiCamera
import argparse
import sys
import time
import numpy as np
import tensorflow as tf
import PIL.Image as Image
Any help is greatly appreciated :)
Since you have not posted the actual errors that you get when you run your code, this is my best guess. First, ensure that exampleScript.py is executable:
chmod +x /home/pi/piNN/exampleScript.py
Second, add a missing leading slash to the shebang in exampleScript.py, i.e. change
'#!usr/bin/env python'
to
'#!/usr/bin/env python'
The setup that you have here is not ideal.
Consider simply importing your other script (make sure they are in the same directory). Importing it will result in the execution of all executable python code inside the script that is not wrapped in if __name__ == "__main__":. While on the topic, should you need to safeguard some code from being executed, place it in there.
I have 2 python file a.py and b.py and I set execute permission for b.py with.
chmod a+x b.py
Below is my sample:
a.py
#!/usr/bin/python
print 'Script a'
import os
script = './b.py'
os.system('"' + script + '"')
b.py
#!/usr/bin/python
print 'Script b'
Execute "python a.py", the result is:
Script a
Script b

How do I import files from other directory in python 2.7

I have been experimenting with python by creating some programs .The thing is, I have no idea how to import something OUT of the default python directory.
OK
So I did some heavy research and the conclusion is
if u want to access a file saved at different location
use
f = open('E:/somedir/somefile.txt', 'r')
r = f.read()
NOTE: Dont use '\' that were I went wrong.Our system addresses uses '\' So be careful
If you need to just read in a file and not import a module the documentation covers this extensively.
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
Specifically for Windows file systems you will need to do one of the following:
1.) Use forwardslashes vs backslashes. This should work with most OSes.
f = open("c:/somedir/somefile.txt", "r")
2.) Use a raw string.
f = open(r"c:\somedir\somefile.txt", "r")
3.) Escape the backslashes.
f = open("c:\\somedir\\somefile.txt", "r")
If you need to import a module to use in your program from outside your programs directory you can use the below information.
Python looks in the sys.path to see if the module exists there and if so does the import. If the path where you files/modules are located is not in the sys.path, Python will raise an ImportError. You can update the path programmatically by using the sys module.
import sys
dir = "path to mymodule"
if dir not in sys.path:
sys.path.append(dir)
import mymodule
You can check the current sys.path by using:
print(sys.path)
Example:
>>> print(sys.path)
['', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python34.zip', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages']
>>> sys.path.append("/Users/ddrummond/pymodules")
>>> print(sys.path)
['', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python34.zip', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages', '/Users/ddrummond/pymodules']
>>>
You can see that sys.path now contains '/Users/ddrummond/pymodules'.

Apache is not interpreting python files

So, I followed this tutorial on Ubuntu 14.04
http://jee-appy.blogspot.in/2015/04/deploy-django-project-on-apache-using.html
Only thing I changed is instead of his example repository,I have used mine.
And I was getting error
Not Found The requested URL / was not found on this server.
Then, I edited my myproject.conf file
Change made - WSGIScriptAlias /myproject /var/www/myproject.wsgi
So, I'm having output Index of/ then directory and file name. it's not interpreting my python files.
Had the same issue and I modified my wsgi file to look like this:
import os
import sys
path = '/var/www/html/YOURAPP/'
if path not in sys.path:
sys.path.append(path)
path = '/var/www/html/YOURAPP/YOURAPP/'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'YOURAPP.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Hope this helps

Unzip zip files in folders and subfolders with python 2.7.8

Continusly to Unzip zip files in folders and subfolders with python this code work with python 3:
#!/usr/bin/env python3
import logging
from pathlib import Path
from shutil import unpack_archive
zip_files = Path(r"C:\Project\layers").rglob("*.zip")
while True:
try:
path = next(zip_files)
except StopIteration:
break # no more files
except PermissionError:
logging.exception("permission error")
else:
extract_dir = path.with_name(path.stem)
unpack_archive(str(path), str(extract_dir), 'zip')
i work with python 2.7.8 and can't change the version of python because it affect other important programs. When i run the code i get an error:
ImportError: No module named pathlib
How can i change the code so it will work?