Opening Blender (a program) from a specific filepath, relative paths, Unix executable - macos

In my previous question, Open a file from a specific program from python, I found out how to use subprocess in order to open a program (Blender) — well, a specific .blend file — from a specific file path with this code.
import os
import subprocess
path = os.getcwd()
os.system("cd path/")
subprocess.check_call(["open", "-a", os.path.join(path, "blender.app"),"Import_mhx.blend"])
With the help of a guy at a forum, I wanted to use relative paths inside the .blend file, so I changed the code in this way (for Windows)
import os
import subprocess
# This should be the full path to your Blender executable.
blenderPath = "/cygdrive/c/Program Files/Blender Foundation/blender-2.62-release-windows32/blender.exe"
# This is the directory that you want to be your "current" directory when Blender starts
path1 = "/Users/user/Desktop/scenario/Blender"
# This makes makes it so your script is currently based at "path1"
os.chdir(path1)
subprocess.check_call([blenderPath, "Import_mhx.blend"])
and for Mac,
import os
import subprocess
path = os.getcwd()
os.system("cd path/")
print (path)
# This should be the full path to your Blender executable.
blenderPath = path + "/blender.app/Contents/macos/blender"
# This is the directory that you want to be your "current" directory when Blender starts
path1 = "/Users/user/Desktop/scenario/Blender"
# This makes makes it so your script is currently based at "path1"
os.chdir(path1)
subprocess.check_call([blenderPath, "Import_mhx.blend"])
Results:
In Windows, it works fine.
On Macs, the result is that the file is opened, but the program seems not to be opened. It is quite strange, I think.
Questions:
Is there any extension that I should place for the blender (UNIX executable file) in order for it to open?
Is there any other way that I can do it in order to open the program correctly, but also be able to use relative paths inside .blend files?

import os
import subprocess
blenderPath = "./blender.app/Contents/MacOS/blender"
path1 = "./"
os.chdir(path1)
subprocess.check_call([ blenderPath, "Animation.blend"])
Both blender opens perfectly and relative paths inside .blend file work ok:)

Related

The pygame window opens and closes immediately [duplicate]

Import pygame
pygame.init()
BG = pygame.image.load('_pycache_/test_bg.jpg')
def DrawGameWin():
window.blit(BG,(0,0))
pygame.display.update()
DrawGameWin()
The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different from the directory of the python file.
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. Alternatively, you can create an absolute file path.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path):
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
An alternative solution is to find the absolute path.
If the file is in an subfolder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the relative filepath. e.g.:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
# join the filepath and the filename
filePath = os.path.join(sourceFileDir, 'test_bg.jpg')
# filePath = os.path.join(sourceFileDir, '_pycache_/test_bg.jpg')
surface = pygame.image.load(filePath)
The same can be achieved with the pathlib module.
Change the working directory
import os, pathlib
os.chdir(pathlib.Path(__file__).resolve().parent)
or create an absolute filepath:
import pathlib
# [...]
filePath = pathlib.Path(__file__).resolve().parent / 'test_bg.jpg'
surface = pygame.image.load(filePath)

How to effectively convert a POSIX path to Windows path with Python in Cygwin?

Problem
Imagine you are writing a Python script which runs on cygwin and calls an external C# executable which requires as input a path.
Assume you cannot change the C# executable in any way.
As you send the path you want to the executable, it rejects all cygwin paths.
So if you pass the path /cygdrive/c/location/of/file.html as a POSIX path, it will fail as the executable requires a Windows path like C:\location\of\file.html
Example:
Message location = os.path.dirname(os.path.realpath(__file__))
os.system('./cSharpScript.exe ' + message_location)
Will result in:
File for the content (/cygdrive/c/location/of/file.html) not found.
Things I've tried so far:
PATH = /cygdrive/c/location/of/file.html
1) path = PATH.replace('/','\\')
Result: File for the content (cygdriveclocationoffile.html) not found.
2) path = os.path.abspath(PATH)
Result: File for the content (/cygdrive/c/location/of/file.html) not found.
os.path.realpath has the same results
I'm probably going in a completely wrong direction with my solutions so far... How would you handle it?
According to [Cygwin]: cygpath:
cygpath - Convert Unix and Windows format paths, or output system path information
...
-w, --windows print Windows form of NAMEs (C:\WINNT)
Example:
[cfati#cfati-5510-0:/cygdrive/e/Work/Dev/StackOverflow/q054237800]> cygpath.exe -w /cygdrive/c/location/of/file.html
C:\location\of\file.html
Translated into Python (this is a rough version, only for demonstrating purposes):
>>> import subprocess
>>>
>>>
>>> def get_win_path(cyg_path):
... return subprocess.check_output(["cygpath", "-w", cyg_path]).strip(b"\n").decode()
...
>>>
>>> print(get_win_path("/cygdrive/c/location/of/file.html"))
C:\location\of\file.html

Python on windows removes created file

I'm trying to write a file with a python program. When I perform all the actions command line, they all work fine. The file is created.
When I perform the actions in a python script, the file does not exist after the script terminates.
I created a small script that demonstrates the behavior.
import os
import os.path
current_dir = os.getcwd()
output_file = os.path.join(current_dir, "locations.js")
print output_file
f = open(output_file, "w")
f.write("var locations = [")
f.write("{lat: 55.978467, lng: 9.863467}")
f.write("]")
f.close()
if os.path.isfile(output_file):
print output_file + " exists"
exit()
Running the script from the command line, I get these results:
D:\Temp\GeoMap>python test.py
D:\Temp\GeoMap\locations.js
D:\Temp\GeoMap\locations.js exists
D:\Temp\GeoMap>dir locations.js
Volume in drive D is Data
Volume Serial Number is 0EBF-9720
Directory of D:\Temp\GeoMap
File Not Found
D:\Temp\GeoMap>
Hence the file is actually created, but removed when the script terminates.
What do I need to do the keep the file?
Problem was solved by changing firewall settings.

Moving files with Wildcards in Python

So I am trying to move say all files starting with "A" to a certain directory. Now I now Windows command prompt does not support this method:
move A* A_Dir
But could this combined with Python find a way? Or am I gonna have to go through each individual file?
Such as:
contents=os.listdir('.')
for file in content:
if file[0] == 'A':
os.system("move %s A_Dir" % file)
... etc. Is there any other solution that is more simpler and quicker?
-Thanks!
On Windows: This example moves files starting with "A" from "C:\11" to "C:\2"
Option #1: if you are using batch file, create batch file (movefiles.bat) as show below:
movefiles.bat:
move /-y "C:\11\A*.txt" "C:\2\"
Execute this batch file from python script as shown below:
import os
batchfile = "C:\\1\\movefiles.bat"
os.system( "%s" % batchfile)
Option #2: using glob & shutil
import glob
import shutil
for data in glob.glob("C:\\11\\A*.txt"):
shutil.move(data,"C:\\2\\")
If we want to move all files and directory starting with A:
import glob
import shutil
for data in glob.glob("C:\\11\\A*"):
shutil.move(data,"C:\\2\\")
Based on #eryksun comment, I have added if not os.path.isdir(data):, if only files starting with A are required to be moved and in this case, directory will be ignored.
import glob
import shutil
import os
for data in glob.glob("C:\\11\\A*"):
if not os.path.isdir(data):
shutil.move(data,"C:\\2\\")

Accessing files within a parent folder and it's sub-folders using Python

I have a folder which has subfolders containing 1000s of DICOM images which I want to read in from IDLE and analyze.
I have used the following code to find file paths:
import sys
print sys.path
I subsequently tried placing my folder which I want to access in these file paths, however I still can not access the files and I get the following error:
>>> fp = open(fp, 'rb')
IOError: [Errno 2] No such file or directory: 'IM-0268-0001.dcm'
I have also tried:
sys.path.insert(0, 'C:/desktop/James_Phantom_CT_Dec_16th/Images')
But this did not work for me either. Help much appreciated, very frustrated.
(using Python 2.7, 64 bit windows OS).
When opening a file, Python does not search the path. You must specify the full path to open:
d = 'C:/desktop/James_Phantom_CT_Dec_16th/Images'
fp = open(d +'IM-0268-0001.dcm',"rb")
Edit: d is the string that will hold the path so that you don't have to re-type it for each file. fp will hold the file object that you will work with. The "rb" is the way you want to open the file:
r - read
w - write with truncate
a - append
r+ - read and write
Also, if working in windows, add "b" to work with binary files. See here.

Resources