4

I have this program Namechange.py which changes names from files (always cuts some useless end). Everything works fine, but I use this file a lot in a lot of different directories, which is bothersome when I want to change something. What I'm searching for is a python script which let's me execute this script in a directory I choose.

My first idea was that I run another script which copies Namechange.py in the desired directory and then executes it there and deletes it after everythings finished. The copying part works. Till now I tried using symlink ( it just executed the script in the working directory :D) as well as the subprocess module, which says there is no such directory when I use:

subprocess.call(["cd", newpath])

newpath is the absolute path to the directory I want to use the script.

with error OSError: [Errno 2] No such file or directory.

If somebody has a elegant way to achieve this I would be glad.

Thanks and goodbye

SourBitter
  • 157
  • 2
  • 11

2 Answers2

5

At the beginning of your script

import os
os.chdir("/dir/to/goto/before/running/the/script")

# rest of the logic goes here

assuming your script is run like this

./my_script dir/to/work/on

then you can do

import os
import sys
os.chdir(sys.argv[1])

# rest of the logic goes here
Ramast
  • 7,157
  • 3
  • 32
  • 32
1

Things you use from anywhere should be reachable from anywhere.

That's where the system's PATH environment variable comes in.

You should either move your script to a directory in the PATH, or extend the PATH with the location of your script.

Note: make sure the script works location-independently: use sys.path extensively, try to use sys.path.join(base, sub) where possible etc...

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • thanks for you answer, brought me to think about the PATH variable in linux systems. What I don't understand is what the join(base, sub) function does. – SourBitter Jan 02 '16 at 16:33
  • PATH is on windows, too. It's actually meant to solve the problem you described. – xtofl Jan 03 '16 at 09:26
  • the `path.join(...)` is especially useful when making scripts that have to work on different platforms (i.e. takes care of forward slash/backward slash/dot/...). Probably not your problem, though. – xtofl Jan 03 '16 at 09:27