![](/img/trans.png)
[英]How to run a Python script portably without specifying its full path
[英]unable to run a python script without specifying full path
您好我正在尝试直接从终端运行 python 脚本。 为此,我已将包含代码的目录添加到我的环境 PATH 变量中。 但是,当我指定完整路径时我能够运行,但当我只调用脚本时却不能。
(base) DS:~ $ /home/user_abc/my_codes/status.py
Everything is ok!
(base) DS:~ $ echo $PATH
/home/user_abc/anaconda3/bin:/home/user_abc/mycodes:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/bin
(base) DS:~ $ status.py
-bash: status.py: command not found
(base) DS:~ $ /status.py
-bash: /status.py: No such file or directory
(base) DS:~ $ ./status.py
-bash: ./status.py: No such file or directory
(base) DS:~ $
我的shebang看起来就是这样。
#!/home/user_abc/anaconda3/bin/python3
(base) DS:~ $ python3 status.py
python3: can't open file status.py': [Errno 2] No such file or directory
(base) DS:~ $ python status.py
python: can't open file 'status.py': [Errno 2] No such file or directory
(base) DS:~ $
虽然我不想要 python 并且只想像任何其他命令一样调用脚本。
您的 PATH 不包括脚本的路径。
您在路径中提到/home/user_abc/mycodes
但 python 脚本的位置在/home/user_abc/my_codes/
下
运行此命令来解决问题。
$ export PATH=$PATH:/home/user_abc/my_codes
$ status.py
您的 PATH 似乎错误。
/home/user_abc/mycodes
应该是/home/user_abc/my_codes
。
那么你至少需要提到这样的相对路径:
$ python my_codes/status.py
另外要了解有关相对路径的更多信息,请参阅此处: 链接
您需要提及 python 因为它不是可执行文件,也就是说,它只是一个脚本,所以我们需要提及我们要执行哪个解释器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.