Hello everyone : I have only one folder under my current directory and I want to go to it by running "cd $(ls)".
So I write this code
import os
os.system("cd $(ls)")
But this did not work for me . Anyone can help to write python syntax to go under the only available folder.
PS : the name of the folder is changeable that's why I want to use "cd $(ls)"
The OS module has some utility functions to achieve what you want to do.
os.listdir(): return a list with all files/directories inside the current working directory
os.chdir(path): changes your working directory
So, you could apply these like:
os.chdir(os.listdir()[0])
It is not obvious if by "go to it" you mean "change current directory for the remaining part of script code" or "change directory to be in after the script exits". If the later, you won't be able to do it - os.system starts a subshell, and changes of current directory in a subshell are not propagated to the parent shell. If the former, you should just use:
import glob, os
os.chdir(glob.glob('*')[0])
Use instead:
os.chdir(os.listdir('.')[0])
Although os.system("cd %(ls)) is correctly working in your shell it will not change the current working directory of your running python interpreter, because os.system() is using a separate shell instance that will be destroyed directly after the execution of the cd shell command.
Double check by executing os.getcwd() before and after (os.getcwd() returns the current working directory of your python interpreter).
Related
I want to change a user's current working directory when they run a Python script. For example, if I have the following script called chdir.py:
import os
os.chdir('Desktop')
I want to be able to do this:
$ pwd
/Users/me
$ python chdir.py
$ pwd
/Users/me/Desktop
I know that os.chdir(path) changes the working directory during the runtime, but it resets when the script exits. Is there any way to prevent this?
I don't think it is possible because the current working directory is an attribute of a process. This means it cannot be changed by another program, such as your python script.
I'm trying to change the terminal directory through a python script. I've seen this post and others like it so I know about os.chdir, but it's not working the way I'd like. os.chdir appears to change the directory, but only for the python script. For instance I have this code.
#! /usr/bin/env python
import os
os.chdir("/home/chekid/work2/")
print os.getcwd()
Unfortunately after running I'm still in the directory of the python script (e.g. /home/chekid) rather than the directory I want to be in. See below.
gandalf(pts/42):~> pwd
/home/chekid
gandalf(pts/42):~> ./changedirectory.py
/home/chekid/work2
gandalf(pts/42):~> pwd
/home/chekid
Any thoughts on what I should do?
Edit: Looks like what I'm trying to do doesn't exist in 'normal' python. I did find a work around, although it doesn't look so elegant to me.
cd `./changedirectory.py`
You can't. The shell's current directory belongs to the shell, not to you.
(OK, you could ptrace(2) the shell and make it call chdir(2), but that's probably not a great design, won't work on Windows, and I would not begin to know how to do it in pure Python except that you'd probably have to mess around with ctypes or something similar.)
You could launch a subshell with your current working directory. That might be close enough to what you need:
os.chdir('/path/to/somewhere')
shell = os.environ.get('SHELL', '/bin/sh')
os.execl(shell, shell)
# execl() does not return; it replaces the Python process with a new shell process
The original shell will still be there, so make sure you don't leave it hanging around. If you initially call Python with the exec builtin (e.g. exec python /path/to/script.py), then the original shell will be replaced with the Python process and you won't have to worry about this. But if Python exits without launching the shell, you'll be left with no shell open at all.
You can if you cheat: Make a bash script that calls your python script. The python script returns the path you want to change directory to. Then the bash script does the acctual chdir. Of course you would have to run the bash script in your bash shell using "source".
The current working directory is an attribute of a process. It cannot be changed by another program, such as changing the current working directory in your shell by running a separate Python program. This is why cd is always a shell built-in command.
You can make your python print the directory you want to move to, and then call your script with cd "$(./python-script.py)". In condition your script actually does not print anything else.
I have a python tile menu script where a subprocess executes a bash shell:
# excute shell script
subprocess.call([self.path + '/pimenu.sh'] + actions)
and in the shell I have:
python ./to/file/name/"$*".py
but when the python script which is found and executed returns an error as it cant find the folder with the images in.:
pygame.error: Couldn't open ./file/name/image.jpg
I am assuming it is looking in the folder the menu script is in, how can I give python or bash the correct path to the scripts resources?
You can use a path finding built in python's os package into the scripts ./to/file/name/"$*".py like this:
import os
print os.getcwd()
It is good enought described into the next SO answer: https://stackoverflow.com/a/3430395/2261861
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.
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")
Use os.chdir:
import os
os.chdir("/home/local/username/project/scrapy/modulename")
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.
see http://docs.python.org/library/os.html
import os
os.chdir(path)
I'm using os.system() to do Windows command line shell executions. I would like to change the Windows cmd current directory. Here's one way of doing it:
os.chdir('newPath')
But chdir() will also change the actual Python current working directory. I don't want to change the actual Python working directory because I want other parts of my script to run in the original current working directory. What I want to change is only the Windows cmd current working directory. In other words: I want os.system() commands to run in one current working directory (Windows cmd current working directory) while anything else should run in another current working directory (the actual Python current working directory).
Here's another try to change only the Windows cmd current directory:
os.system('cd newPath')
However, that obviously doesn't work since right after the execution of the cd newPath command the Windows cmd current directory is reset (because I won't use the same Windows command shell in the next call to os.system()).
Is it possible to have a separate current working directory for the Windows cmd shell? (separate from the actual current working directory).
The subprocess module is intended to replace os.system.
Among other things, it gives you subprocess.Popen(), which takes a cwd argument to specify the working directory for the spawned process (for exactly your situation).
See: http://docs.python.org/library/subprocess.html
Example usage replacing os.system:
p = subprocess.Popen("yourcmd" + " yourarg", shell=True, cwd="c:/your/path")
sts = os.waitpid(p.pid, 0)[1]
If it only has to work on Windows, one way might be:
os.system('start /d newPath cmd')
When you use os.system, you're not reusing the same command shell, but spawning a new one for each request. This means that you can't actually expect changes in it to propagate between invocations.
You could write a wrapper though, that will always change to the directory you want before launching the command.