3

I'm writing a Python script to automate installation of UWP-Apps. The script uses Dependencies inside the script directory; my older scripts use this code:

os.chdir(os.path.dirname(sys.argv[0]))

The above code doesn't work on my current script but works fine on older scripts. It shows:

OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''

Researching this topic, I only found talk about running the script from outer/different directory.

1
  • No, it didnt require such. In fact, its working as like: cd /d "%~dp0" Commented Oct 13, 2021 at 13:40

2 Answers 2

6
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Thanks for the help! It works but need to use work-around, usefull if im placing the depedencies on the temp folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.