When I start program like this
python Script.py
abspath return sth like that
os.path.abspath("../../house/kitchen") == "/ex1/ex2/house/kitchen"
But when i start like this i got
python ex3/Script.py
os.path.abspath("../../house/kitchen") == "/house/kitchen"
I think i need to set working place to place where is script but how to do that.
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
This solved my problem
When given a relative path argument, abspath starts from your current directory, not the current directory of the script, so if your current directory changes the output changes.
Related
I have read way to many threads now and really lost.
Just trying to do something basic before I make it complicated.
so i have a script test.py
I want to call the script from within runme.py but without waiting so it will process the other chunk of code, but then when it gets to the end wait for test.py code to finish before continuing on.
I cant seem to figure out the correct syntax for the p = subprocess.Popen (I have tried so many)
and do I need the that to the test.py if its in the same directory?
here is what i have but cant get to work.
import subprocess
p = subprocess.Popen(['python test.py'])
#do some code
p.wait()
I cant seem to figure out the correct syntax for the p = subprocess.Popen (I have tried so many)
You want to pass it a list of arguments. The first argument is the program to run, python (although actually, you probably want sys.executable here); the second is the script that you want python to run. So:
p = subprocess.Popen(['python', 'test.py'])
and do I need the that to the test.py if its in the same directory?
This will work the same way as if you ran python test.py at the shell: it will just pass test.py as-is to python, and python will treat that as a path relative to the current working directory (CWD).
So, if test.py is in the CWD, this will just work.
If test.py is somewhere else, then you need to provide either an absolute path, or one relative to the CWD.
One common thing you want is that test.py is in not necessarily in the CWD, but instead it's in the same directory as the script/module that wants to launch it:
scriptpath = os.path.join(os.path.dirname(__file__), 'test.py')
… or in the same directory as the main script used to start your program:1
scriptpath = os.path.join(os.path.dirname(sys.argv[0]), 'test.py')
Either way, you just pass that as the argument:
p = subprocess.Popen(['python', scriptpath])
1. On some platforms, this may actually be a relative path. If you might have done an os.chdir since startup, it will now be wrong. If you need to handle that, you want to stash os.path.abspath(os.path.dirname(sys.argv[0])) in the main script at startup, then pass it down to other functions for them to use instead of calling dirname(argv[0]) themselves.
I currently have a macro that calls a python executable. However when I run the macro it doesnt seem to run. I know it's not a problem with the executable because when I double click on it it runs fine. I also don't think its a problem with the filepath.
What other possible problems could there be.
I've been working on this for the past 8 hours.
Relevant Code:
folderPath = Application.ActiveWorkbook.Path
Dim stAppName As String
stAppName = folderPath & "\dist\MCM_MAT2.exe"
Call Shell(stAppName, 1)
It sounds like your working directory needs to be set before you call the shell.
' Go to the desired startup directory.
ChDir folderPath
I'm having an extremely frustrating experience attempting to change directories in python using variables within the program. Specifically, suppose I have:
index = '999'
os.environ['dir_name'] = 'Directory_Name_' + index
os.chdir('$dir_name')
gives OSError: [Errno 2] No such file or directory: '$dir_name'
and yet
os.system('echo $dir_name')
returns 'Directory_Name_999' (a valid directory name)
and similarly
os.chdir('Directory_Name_999')
changes the directory without error.
Where am I going wrong here?
You're confusing what os.system can do and what Python can do. os.system understands that $dir_name is a variable named dir_name. It checks its environment variables and finds it.
Python has no idea what "$dir_name" is, and assumes you're using a literal string. It tries to change the directory to that, and fails since there is no literal directory "$dir_name".
Instead, do:
index = '999'
os.environ['dir_name'] = "Directory_Name_"+index
os.chdir(os.environ['dir_name'])
You could also have os.system change your directory, since it knows what "$dir_name" means:
os.system('cd $dir_name')
But why muck with system calls? Just have Python do it.
For others looking for the same thing you can do this:
index = '999'
dir_name = "Directory_Name_"+index
os.chdir(dir_name)
Hope this helps.
Actually need to go some path and execute some command and below is the code
code:
import os
present_working_directory = '/home/Desktop/folder'
presently i am in folder
if some_condition == true :
change_path = "nodes/hellofolder"
os.chdir(change_path)
print os.getcwd()
if another_condition == true:
change_another_path = "nodes"
os.chdir(change_another_path)
print os.getcwd()
**Result**:
'/home/Desktop/folder/nodes/hellofolder'
python: [Errno 1] No such file or directory
Actually whats happening here is when i first used os.chdir() the directory has changed to
'/home/Desktop/folder/nodes/hellofolder',
but for the second one i need to run a file by moving to one folder back that is
'/home/Desktop/folder/nodes'
So can anyone let me how to move one folder back in python
Just like you would in the shell.
os.chdir("../nodes")
Here is a very platform independent way to do it.
In [1]: os.getcwd()
Out[1]: '/Users/user/Dropbox/temp'
In [2]: os.path.normpath(os.getcwd() + os.sep + os.pardir)
Out[2]: '/Users/user/Dropbox/'
Then you have the path, and you can chdir or whatever with it.
Just call
os.chdir('..')
the same as in any other language :)
Exact answer for your question is os.chdir('../')
Use case:
Folder1:
sub-folder1:(you want to navigate here)
Folder2:
sub-folde2:(you are here)
To navigate to sub-folder1 from sub-folder2, you need to write like this
"../Folder1/sub-folder1/"
then, put it in os.chdir("../Folder1/sub-folder1/").
think about using absolute paths
import os
pwd = '/home/Desktop/folder'
if some_condition == true :
path = os.path.join(pwd, "nodes/hellofolder")
os.chdir(path)
print os.getcwd()
if another_condition == true:
path = os.path.join(pwd, "nodes")
os.chdir(path)
print os.getcwd()
My problem was fixed with this command
first import os and after add
os.path.normpath(os.path.abspath(__file__) + os.sep + os.pardir)
The answers mentioned above are correct. The following is more a
It usually happens when your Python script is in a nested directory and you want to go one level up from the current working directory to maybe let's say load a file.
The idea is to simply reformat the path string and prefix it with a '../'. So an example would be.
'../current_directory/' + filename
This format is similar to when used in a terminal. Whenever in doubt fire up a terminal and experiment with some commands. The format is reflected in the programming language.
Define this function in your script and call it whenever you want to go back just by one folder:
import os
def dirback():
m = os.getcwd()
n = m.rfind("\\")
d = m[0: n+1]
os.chdir(d)
return None
I chrooted directory using following commands:
os.chroot("/mydir")
How to return to directory to previous - before chrooting?
Maybe it is possible to unchroot directory?
SOLUTION:
Thanks to Phihag. I found a solution. Simple example:
import os
os.mkdir('/tmp/new_dir')
dir1 = os.open('.', os.O_RDONLY)
dir2 = os.open('/tmp/new_dir', os.O_RDONLY)
os.getcwd() # we are in 'tmp'
os.chroot('/tmp/new_dir') # chrooting 'new_dir' directory
os.fchdir(dir2)
os.getcwd() # we are in chrooted directory, but path is '/'. It's OK.
os.fchdir(dir1)
os.getcwd() # we came back to not chrooted 'tmp' directory
os.close(dir1)
os.close(dir2)
More info
If you haven't changed your current working directory, you can simply call
os.chroot('../..') # Add '../' as needed
Of course, this requires the CAP_SYS_CHROOT capability (usually only given to root).
If you have changed your working directory, you can still escape, but it's harder:
os.mkdir('tmp')
os.chroot('tmp')
os.chdir('../../') # Add '../' as needed
os.chroot('.')
If chroot changes the current working directory, you can get around that by opening the directory, and using fchdir to go back.
Of course, if you intend to go out of a chroot in the course of a normal program (i.e. not a demonstration or security exploit), you should rethink your program. First of all, do you really need to escape the chroot? Why can't you just copy the required info into it beforehand?
Also, consider using a second process that stays outside of the chroot and answers to the requests of the chrooted one.