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)
Related
I am writing a program that needs to know which Drive is Windows drive . because I need to go to "Windows-Drive:\Users\publick\Desktop", I need some code or module that will give me the windows drive.
Thanks for your kindness.
If what you really want is the drive where Windows is installed, use
import os
windows_drive = os.environ['SystemDrive']
But it looks like what you actually need is the public desktop folder. You can get that easier and more reliably like this:
import os
desktop_folder = os.path.join(os.environ['PUBLIC'], 'Desktop')
For the current user's desktop folder instead, you can use this:
import os
desktop_folder = os.path.join(os.environ['USERPROFILE'], 'Desktop')
But I'm not sure that the desktop folder is always called 'Desktop' and that it's always a subdirectory of the profile folder.
There is a more reliable way using the pywin32 package (https://github.com/mhammond/pywin32), but it obviously only works if you install that package:
import win32comext.shell.shell as shell
public_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_PublicDesktop)
user_desktop_folder = shell.SHGetKnownFolderPath(shell.FOLDERID_Desktop)
(Unfortunately pywin32 is not exactly well documented. It's mostly a matter of first figuring out how to do things using Microsoft's Win32 API, then figuring out where to find the function within pywin32.)
#!/usr/bin/env python3
# Python program to explain os.system() method
# importing os module
import os
# Command to execute
# Using Windows OS command
cmd = 'echo %WINDIR%'
# Using os.system() method
os.system(cmd) # check if returns the directory [var = os.system(cmd) print(var) ] in Linux it doesnt
# Using os.popen() method
return_value = os.popen(cmd).read()
can you check this approach ? I am not on Win
I found my Answer!
`import os
Windows-Drive=os.path.dirname(os.path.dirname(os.path.join(os.path.join(os.environ['USERPROFILE']))))
This code is answer!
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).
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
In my script, I need to bring up the command prompt which I have not had any issues in creating:
subprocess.Popen([r"cmd.exe"])
That is essentially what I have done so far. I have some arguments that want to be placed in this prompt, that I want automatically ran when I run the script.
What I would like to do is change my directory in the prompt using only Python. Would anybody have any idea how to get there?
subprocess.Popen takes a keyword argument to specify the current working directory. Simply do this:
subprocess.Popen(r"cmd.exe", cwd = "my/lovely/directory/", "more-args")
Well I have no idea about subprocess, but you could use the os module to change directories, start command prompt, run a batch program, etc.
import os
os.chdir('blah')
os.system('start something.bat')
Depends on if you strictly need to use subprocess. Hope that helps though!
My coworker is having trouble with a Python install. When running the code below, from 'C:\my\folder\', 'C:\' is returned instead of the current working directory. When I or anyone else run the script on our systems, we get 'C:\my\folder\'.
We're assuming that some global setting must be causing the issue, so I've had the person uninstall Python, delete the local Python2.7 folder, clean the registry and reinstall the Python, but it's still not working.
NOTE: We have a large number of legacy scripts, so revising all of them to use subprocess is impractical. :(
Any ideas?
Environment: Windows XP, Python 2.7
import os
#
# This test script demonstrates issue on the users computer when python invokes
# a subshell via the standard os.system() call.
#
print "This is what python thinks the current working directory is..."
print os.getcwd()
print
print
print "but when i execute a command *from* python, this is what i get for the current working directory"
os.system('echo %cd%')
raw_input()
you could also try something like this
os.chdir("C:\\to\\my\\folder")
print os.system("echo %CD%")
raw_input()
also to get the current working directory i use a different approach
cur_dir = os.path.abspath(".")
os.getcwd() isn't guarenteed to get the location of your script when it is called. Your coworker might be calling the script a different way or his computer (for some reason) handles the current working directory differently.
To get the actual script location you should use the following:
import os
os.path.dirname(os.path.realpath(__file__))
As an example I wrote getcwd and the above line in the same script and ran it from C:\.
Results:
C:\>python C:\Users\pies\Desktop\test.py
C:\Users\pies\Desktop
C:\
It depends on what your real purpose for this script is, whether you actually need the current working directory, or just the current scripts directory. As a little caveat this call will return a different directory if you call a script from script which then uses this call.
os.system("cd dir;command params")