I have set my path environment variable to include the python interpreter as well as my "python_scripts" folder. I can call the python interpreter or any .py files located in my "python_scripts" folder individually from anywhere on my machine as follows:
C:\> python.exe
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
or
C:\> test_code.py
and they both work fine. However, when I call the python interpreter followed by the script name:
C:\> python.exe test_code.py
it returns with the following error unless I'm located in my "python_scripts" folder:
python: can't open file 'test_code.py': [Errno 2] No such file or directory
Why would this be happening?
If you use C:\\> python.exe test_code.py
it will look in your current directory for test_code.py
. If you pass an argument to python.exe
it needs to be a valid absolute or relative path to a file that exists.
That means that the file is on your Windows %PATH%
variable. When you do python.exe
, it looks in all sorts of places. For example, if your PATH
looked like: C:\\;"C:\\Program Files\\Python 3\\";C:\\Users\\user\\python_scripts
, it would try C:\\python.exe
, then try C:\\Program Files\\Python 3\\python.exe
and find Python.
When you do test_code.py
, it finds it as C:\\Users\\user\\python_scripts\\test_code.py
(For example).
When you call python.exe
, it just reads the filename and does not try to resolve the path.
Python uses a different path for importing, which can be seen as sys.path
.
You can extend this using a .pth
file in python\\Lib\\site-packages
.
For example, if you add a user_pth.pth
file with this content:
C:\Users\user\python_scripts\
Then you can do import test_code
from any file.
So, you can invoke pythons importer by running your code as a module:
python.exe -m test_code
you should give python.exe the full path to your script python.exe. c:\\test_code.py
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.