Change current directory for user in Python - python

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.

Related

linux command using python to go under a specific folder

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).

Running Tensorflow script from another location

I have created Tensorflow image classifier and image classifier should be called using another python script.
I tried os.system() but I cant just call Tensorflow scripts coz it's depends on the multiple files in the Tensorflow script location. so I have to include all the files with classifier script in the main script(2nd python script).
What is the best way to do this?
when script is running :
script error when running from another location :
Do you have tried Python Subprocess instead of os.system?
From How do you use subprocess.check_output() in Python? you can see this simple demo:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
UPDATE:
I think your problem it that you need to specify/set the correct folder path before running your python script. For example:
Consider you have the following folder structure:
/root/project/script.py
/root/project/data/file.txt
If in your python script you load a file using a relative path like ./data/file.txt, you need to run your script inside the project folder.
If you run it in the root folder, like this:
/root$ python project/script.py
the script fails, because it tries to find the data/file.txt inside the root folder.
You can use the cd command to change the current directory before running your python script. You can do it while calling the os.system, like this:
os.system("cd project && python script.py") # for my example case
whereever you call your python script from, all relative paths in your script will be based on. i.e. you called the script from its project folder in the first image, so the links to project_folder/tf_files/... were working, whereas you lateron called it from elsewhere, so that the symbolic links were messed up. your script tried to find elsewhere/tf_files/... but that subfolder does not exist.
you could edit the script so all paths are always abolute (starting with /home/...), then there is no way of confusing the

How do I change directory in python so it remains after running the 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.

Run python function in shell script

Let's say I want to use a shell script to run a python file, called test.py, which is in a directory called Test in my home directory. I tried the following code, which does not work:
#!/bin/bash
echo "Starting."
module load gcc/4.8.2
module load python/3.4.1
echo "Modules loaded."
$HOME/Test/test.py
exit 0
I do not believe that how I am trying to run the program ($HOME/Test/test.py) works. I have not been able to determine how to do this, despite searching for a long time. Any help would be appreciated.
This is likely one of the following, or it may be a combination of both.
The python script is not executable. Fix with:
chmod u+x $HOME/Test/test.py
The script does not start with a #! line pointing to python. Fix that by making this the first line of test.py:
#!/usr/bin/env python
You can also use a full path instead of using /usr/bin/env to use $PATH to resolve the name.
#!/usr/local/bin/python

how to enter in to a folder through python code on linux

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)

Categories

Resources