How do I open a terminal where the python file is executed - python

I made a script that when clicked on it copies all the files of the directory where it was opened in on to a USB.
It works inside Pycharm but when I convert it to an executable (When I use pyinstaller to convert the .py to a .exec) it does not work.
I’m almost certain I know what’s wrong but I don’t know how to fix it.
import shutil
import os
current = os.getcwd()
list_of_files = os.listdir(current)
def get_files():
print('CURRENT: ' + current)
print('File_List: ' + str(list_of_files))
for files in list_of_files:
shutil.copy(current + '/' + files, '/Volumes/U/Copy_things')
get_files()
Long story short I’m using os.getcwd() so the file knows where it is located.
When I execute the file in Pycharm the current directory that os.getcwd() gives me is
CURRENT: /Users/MainFrame/Desktop/python_test_hub/move_file_test
But when I open the executable (same folder as the .py file ) and the terminal opens up os.getcwd() gives me is
CURRENT: /Users/MainFrame
So I need to find a way for the executable to open up the terminal where it is located so it can copy those files.
I want to be able to execute it from any folder and copy the files to a USB.

os.getcwd() gets the directory of where the script is executed from, and this isn't necessarily where you're script is located. Pycharm is most likely altering this path when executing the script, as it executes your script from the project path, rather than the python path.
Try os.path.abspath(os.path.dirname(os.sys.argv[0])) instead of os.getcwd().
These answers have more information: os.getcwd() vs os.path.abspath(os.path.dirname(__file__))
Difference between __file__ and sys.argv[0]

Related

Run Python Script From Script Directory/Current Directory

[Introduction]
Hi! I'm working on a python script to automate installation of UWP-Apps, it's been a long time i'm not touching Python; until this day. The script uses Depedencies inside the script directory, i've looking up on my older scripts and found this specific code.
os.chdir(os.path.dirname(sys.argv[0]))
[Problematic]
However, using the above code doesn't work on my current script but it's working fine on older scripts. When using above, it shows:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
Already looking up on Internet about this topic; but most of them was talking about running the script from outer/different directory that leads me to dead end.
Any helps is appreciated :)
The easiest answer is probably to change your working directory, then call the .py file from where it is:
cd path/to/python/file && python ../.py
Of course you might find it even easier to write a script that does it all for you, like so:
Save this as runPython.sh in the directory where you're running the python script from, is:
#!/bin/sh
cd path/to/python/file
python ../script.py
Make it executable (for yourself):
chmod +x ./runPython.sh
Then you can simply enter your directory and run it:
./runPython.sh
If you want to only make changes to the python script:
mydir = os.getcwd() # would be the folder where you're running the file
mydir_tmp = "path/to/python/file" # get the path
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd()
The reason you got an error was because sys.argv[0] is the name of the file itself, instead you can pass the directory as a string and use sys.argv[1] instead.
import os
from os.path import abspath, dirname
os.chdir(dirname(abspath(__file__)))
You can use dirname(abspath(__file__))) to get the parent directory of the python script and os.chdir into it to make the script run in the directory where it is located.

python - error occurs on relative path but not absolute path in macOS

I'm having a strange issue. I'm just trying to do a basic show directory contents for relative path.
Created a test directory on the desktop
test directory contents
test.py
test1 -- folder
sample.txt
contents of test.py
import os
dataDir = "test1"
for file in os.listdir("/Users/username/Desktop/test"):
print(file)
Summary - absolute path
works - in visual studio code
works - macOS terminal python3 /Users/username/Desktop/test/test.py
however when use the variable I get an error:
contents of test.py
import os
dataDir = "test1"
for file in os.listdir(dataDir):
print(file)
Summary - relative path
works - in visual studio code
ERROR - macOS terminal python3 /Users/username/Desktop/test/test.py
Traceback (most recent call last):
File "/Users/username/Desktop/test/test.py", line 4, in
for file in os.listdir(dataDir):
FileNotFoundError: [Errno 2] No such file or directory: 'test1'
I all depends on what folder you are in when you launch the code.
Let's say your .py file is in folder1/folder2/file.py and your test1 folder is folder1/folder2/test1/.... You open a terminal in the folder1 and launch python3 /folder2/file.py. The program is going to check for files in folder1/test1/.
Try navigating to the actual file folder, that should work. If you want to use it wherever you launch the code you will have to do some checks on the current directory and manually point the code to the wanted path.
The following solution is inspired by that answer
A simple way to solve your problem is to create the absolute path. (I recommend using that always when you're working with different directories and files)
First of all, you need to care about your actual working directory. While using VS Code your working directory is in your desired directory (/Users/username/Desktop/test/).
But if you use the command line your actual working directory may change, depending where you're calling the script from.
To get the path where script is actually located, you can use the python variable __file__. __file__ is the full path to the directory where your script is located.
To use your script correctly and being able to call it using both ways, the following implementation can help you:
import os
dataDir = "test1"
# absolute path to the directory where your script is in
scriptDir = os.path.dirname(__file__)
# combining the path of your script and the 'searching' directory
absolutePath = os.path.join(scriptDir, dataDir)
for file in os.listdir(absolutePath):
print(file)

WinError 5 access is denied - renaming files - Python

I have been trying to create an executable for a simple file name converter.
the goal is to rename all files from a certain directory to their creation date (for images).
import datetime
import os
from tkinter.filedialog import askdirectory
path = askdirectory(title='Select Folder') # shows dialog box and return the path
os.chdir(path)
files = os.listdir(path)
for filename in files:
time_stamp = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
os.rename(filename, time_stamp.strftime('%d-%m-%Y %H-%M-%S') + ".jpg")
It works perfectly where I run it through PyCharm, but when I run it through the executable that I created using pyInstaller, I get "[WinError 5] access is denied". The premission error occures because of the os.rename() function.
I tried to run it as an administrator but I got the same result.
I also updated my python, pycharm and pip but that had no effect.
Is there a way to make this script an executable?
thank you all

Python current working directoy set to home path instead of script dir

Why don't I get a json file written to disk in the current working directory (script location) when executing the following script? Shouldn't dump() do this?
def getShotFolders():
shotDict = {
"root" : shotExample,
"shot_subdirs" : []
}
for root, dirs, files in os.walk(shotExample, topdown=False):
if root != shotExample:
shotDict["shot_subdirs"].append(os.path.relpath(root,shotExample))
pprint(shotDict)
with open("shot_folderStructure.json", "w") as write_file:
json.dump(shotDict, write_file )
getShotFolders()
EDIT: Ok, I run my python files from vscode with right click 'execute python file in terminal' which outputs the C:/Python27/python.exe c:/Users/user/Desktop/test.py command.
If I run the script from pycharm with the same python set as the project interpreter the json files are created, but why?
EDIT2: ok for some reason when I execute the script the cwd is my home folder, shouldn't it be to the path of the python script. I know this can be fixed by os.chdir(os.path.dirname(__file__)) but it shouldn't be this way right?
Make sure you are opening your C:\Users\user\Desktop folder in VS Code in order to set the cwd to your desktop (if you open the file directly then it won't change your working directory).

Open a file from a specific program from python

I would like to do a very simple thing but I am quite lost.
I am using a program called Blender and I want to write a script in python which open a .blend file but using the blender.app which is located in the same folder with the blend file, not with the blender.app which is located in Applications. (using Macosx)
So I was thinking that this should do the job...but instead it opens blender twice...
import os
path = os.getcwd()
print(path)
os.system("cd path/")
os.system("open blender.app Import_mhx.blend")
I also tried this one
import os
path = os.getcwd()
print(path)
os.system("cd path/")
os.system("open Import_mhx.blend")
but unfortunately it opens the .blend file with the default blender.app which is located in Applications...
any idea?
This cannot work since the system command gets executed in a subshell, and the chdir is only valid for that subshell. Replace the command by
os.system("open -a path/blender.app Import_mhx.blend")
or (much better)
subprocess.check_call(["open", "-a", os.path.join(path, "blender.app"),
"Import_mhx.blend"])
Have you tried telling the open command to open it WITH a specific application?
open -a /path/to/blender.app /path/to/Import_mhx.blend
Your first attempt was on the right track but you were really telling open to just open two different things. Not one with the other.

Categories