1

I am working on python(scrapy), i am trying to enter in to a folder by using os module but unable to do it, below is what i have tried

import os

scrapepath = "cd /home/local/username/project/scrapy/modulename"

os.system(scrapecmd)

Result:

0

Finally my intention is to enter in to a folder(Destination) from some where (for example home in linux) through python code as i mentioned above. Here actually i am generating some part of the path above dynamically and after that i should enter in to that path and run some commands from inside that folder

Can any one please let me know how to enter to a folder by using python code in linux as above.

Shiva Krishna Bavandla
  • 25,548
  • 75
  • 193
  • 313
  • why don't you want to run the command directly ? e.g., subprocess.call(["/path/to/my/command", "arg1", "arg2"]) – John Wang Aug 31 '12 at 11:36
  • @JohnWang: There are certainly plenty of programs out there where the working directory is relevant to behavior. – Wooble Aug 31 '12 at 11:38
  • http://stackoverflow.com/questions/431684/how-do-i-cd-in-python – Rakesh Aug 31 '12 at 11:42
  • i am working on scrapy actually, i dont want to run command directly because i will create number of scrapy folder which consists of individual spider names each, so need to enter in to each folder and need to run command through that spider name – Shiva Krishna Bavandla Aug 31 '12 at 11:44

4 Answers4

3

Use os.chdir:

import os

os.chdir("/home/local/username/project/scrapy/modulename")
orlp
  • 112,504
  • 36
  • 218
  • 315
3

To change the current working directory:

os.chdir("/home/local/username/project/scrapy/modulename")

You might also like to simply add that module to python's path (which is where import looks):

sys.path.append("/home/local/username/project/scrapy/modulename")
Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • As an addition- the reason that `os.system` doesn't work in the original question, is that `os.system` creates a new process - changes the directory __in that process__ and then closes the process. – Tony Suffolk 66 Apr 07 '16 at 21:08
2

AFAIK, os.system() executes the string command in a subshell. So, when you execute something like:

os.system("cd /path/to/directory/")

The cd command will actually be executed in a subshell. But, as the subshell exits after os.system execution, your cd has no practical effect for your application.

Valdir Stumm Junior
  • 4,568
  • 1
  • 23
  • 31
1

see http://docs.python.org/library/os.html

import os
os.chdir(path)