Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Python Script From Script Directory/Current Directory

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.

like image 666
MC874 Avatar asked Dec 13 '25 10:12

MC874


2 Answers

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.

like image 176
leaves Avatar answered Dec 16 '25 00:12

leaves


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.

like image 34
kinshukdua Avatar answered Dec 15 '25 23:12

kinshukdua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!