简体   繁体   中英

How to get the directory from which a python executable is being called?

A Python 3 program has been compiled into an exe file called myapp.exe , and is located at a C:\path\to\myapp.exe or at /path/to/myapp.exe using pyinstaller.

Another program calls the executable from some other arbitrary location anywhere on the same machine. For example, from C:\another\arbitrary\path\ or from /another/arbitrary/path/ .

My question is:
What specific syntax must be added to the code that gets compiled into myapp.exe in order for myapp.exe to be able to programmatically refer to the other arbitrary path from which myapp.exe is being called at any given point in time?

Current Code:

The current code for the myapp.py file that gets compiled into myapp.exe is:

print('Hello World!')

Desired Code:

The desired code after you answer this question should look something like:

yourCallingDirectoryAtAnotherArbitraryPath = code requested in this OP
print('Hello, you are calling from ', yourCallingDirectoryAtAnotherArbitraryPath)

This must work for any OS.

If you are one of those who voted to close this question, please either answer, or please state what can be clarified to make this question easier to answer.

Usually the more difficult job is for the executable to find out where it is stored itself. When you start a program, the current directory is available to the executable with the shorthand pathname .

So to get the absolute path of the current directory, it is as easy as:

import os
print (os.path.abspath("."))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM