Home > database >  Run Python Script From Script Directory/Current Directory
Run Python Script From Script Directory/Current Directory

Time:10-13

[Introduction]

Hi! Im working on a python script to automate installation of UWP-Apps, its been along time im not touching Python again until this day. The python script uses Depedencies from the script directory itself, i have been looking up on my older scripts and found the specific code.

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

[Problematic]

However, the using the above codes doesnt work on my current script but its working on older scripts. When using above, it shows:

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

I have been looking up on Internet but most of them was talking about running the script from outer/different directory that leads me to the end. Any helps is appreciated :)

CodePudding user response:

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 puthon script from is:

#!/bin/sh
cd path/to/python/file
python ../script.py

Make it executable:

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.

CodePudding user response:

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 main python script and os.chdir into it to make the script run in the directory where it is located.

  • Related