[英]Open python script using command line
I created python script ( "hello.py" for example). 我创建了python脚本(例如“ hello.py” )。 But I would like to open script from any directory using: 但是我想使用以下命令从任何目录打开脚本:
darker0n@MacBook ~>hello
Create a custom command that'll invoke your Python script. 创建一个自定义命令,该命令将调用您的Python脚本。
Let's say your hello.py
is in the path /home/python/hello.py
假设您的hello.py
位于/home/python/hello.py
路径中
Create a custom script called hello
containing: 创建一个名为hello
的自定义脚本,其中包含:
python /home/python/hello.py
. python /home/python/hello.py
。
You can put it a hidden directory so that it remains hidden. 您可以将其放置为隐藏目录,以使其保持隐藏状态。
Say you've added it to the following file: /home/python/.custom/hello
. 假设您已将其添加到以下文件: /home/python/.custom/hello
。 Now add the following line to your .bashrc
(or equivalent) file: 现在, .bashrc
下行添加到您的.bashrc
(或等效文件)文件中:
export PATH=$PATH":/home/python/.custom
Next time you open a terminal and type hello
, you get the script to run. 下次打开终端并输入hello
,将运行脚本。 To get it immediately in any already open terminal sessions, simply run source ~/.bashrc
要在任何已经打开的终端会话中立即获取它,只需运行source ~/.bashrc
Use a shell interpreter line, (shebang line). 使用shell解释器行(shebang行)。 For example, in a file called hello. 例如,在名为hello的文件中。
#!/usr/bin/env python
python code here
...
then 然后
chmod +x hello
and put the hello script somewhere in your PATH. 并将hello脚本放在PATH中。
Oh and don't type 哦,不要打字
~>hello
that is a syntax error, and the > will redirect output to a file hello, overwrite it with nothing, as the "~" is not really a command, but a special shell $HOME directory spec. 这是一个语法错误,>会将输出重定向到一个文件hello,不覆盖任何内容,因为“〜”不是真正的命令,而是特殊的shell $ HOME目录规范。 Unless the ~> is part of your prompt, then ignore this warning. 除非〜>是提示的一部分,否则请忽略此警告。
You can create a symbolic link in your /usr/local/bin
folder (or any folder in your PATH env variable) with the command: 您可以使用以下命令在/usr/local/bin
文件夹(或PATH env变量中的任何文件夹)中创建符号链接:
ln -s /path/to/hello.py /usr/local/bin/hello
This will allow to keep your script in your preferred path and having the possibility to modify it anytime. 这将使您的脚本保持在您的首选路径中,并可以随时对其进行修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.