简体   繁体   中英

$PATH has the correct entry, but python fails to execute

I have my PATH variable to point to my-project directory. However when I try to run the python script from outside it does not work. May be it tooks simple, but i am not able to find an answer. I have googled and done it right. Please help me point out the mistake.

Also, I have added the path to my.bash_profile but not working:

root@c3-redsuren-vm01:~# cat .bash_profile
export PATH="$PATH:/opt/mssql-tools/bin:/root/my-project"

root@c3-redsuren-vm01:~/my-project# python print_test.py
hello world
root@c3-redsuren-vm01:~/my-project# ./print_test.py
hello world

Going back to home dir which is /root

root@c3-redsuren-vm01:~/my-project# cd ~
root@c3-redsuren-vm01:~# pwd
/root

Try to execute script from home dir:

root@c3-redsuren-vm01:~# python print_test.py
python: can't open file 'print_test.py': [Errno 2] No such file or directory
root@c3-redsuren-vm01:~# ./print_test.py
-bash: ./print_test.py: No such file or directory
root@c3-redsuren-vm01:~# python print_test.py
python: can't open file 'print_test.py': [Errno 2] No such file or 
directory

Path details:

root@c3-redsuren-vm01:~# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/mssql-tools/bin:/root/my-project
root@c3-redsuren-vm01:~#

root@c3-redsuren-vm01:~/my-project# python print_test.py
hello world

If I go to the my-project directory and run the script it works fine. Thanks in advance!

The argument to Python should be a file name; Python does not examine your PATH to look in directories other than the current directory.

The standard way on Linux-like systems to make a script executable from anywhere is to put in a valid shebang and mark the script itself as executable and save it in a directory which is in your PATH ; then you can run it from anywhere with just the file name.

bash$ pwd
/root
bash$ echo "$PATH" | tr ':' '\n' | grep my_project
/root/my_project
bash$ cat >my_project/print_test
#!/usr/bin/env python
print('hej världen')
^D
bash$ chmod +x my_project/print_test
bash$ print_test
hej världen

(You might have to hash -r print_test before the last command actually works.)

the python interpreter uses the path variable for only importing the modules. If you want to run as script, then it will depend on initial path of interpreter.

You can check the current paths by:

import sys
print(sys.path)

for your case, if you want to run "print_test.py" from anywhere, you use it as module.

And append the path like:

sys.path.append('/opt/mssql-tools/bin:/root/my-project')
import print_test #this would execute the script 

If you want to do without moduling, can check this: https://www.geeksforgeeks.org/run-python-script-from-anywhere-in-linux/

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