简体   繁体   English

在当前 shell 中运行 python 脚本

[英]run python script in current shell

When I need to run a bash script that runs cd somedir to affect the current shell I run it with . scriptname当我需要运行运行cd somedir来影响当前 shell 的 bash 脚本时,我使用. scriptname . scriptname . . scriptname However, if scriptname is a python script even with #!/usr/bin/env python3 in the first line, it doesn't work, it seems it expects the script to be a bash script.但是,如果scriptname是 python 脚本,即使第一行中带有#!/usr/bin/env python3 ,它也不起作用,它似乎希望脚本是 bash 脚本。 How can I make it work with python scripts (or any other language with the appropriate shebang)?我怎样才能让它与 python 脚本(或任何其他具有适当 shebang 的语言)一起工作?

It is not possible.这不可能。

The only thing that can affect current process environment is the process itself.唯一能影响当前流程环境的是流程本身。 Because the current shell is bash, the only thing that can be executed that could affect bash environment is something that can be run by bash itself.因为当前的shell是bash,所以唯一能影响bash环境的就是能被bash自己运行的东西。 That "something" are statements interpreted by bash.那个“东西”是由 bash 解释的语句。 Because bash doesn't support interpreting and running python statements, it is not possible.因为 bash 不支持解释和运行 python 语句,所以这是不可能的。

The usual way around this, is to output from your python script properly escaped assignment statements that would assign environment variables.解决此问题的常用方法是从 Python 脚本中输出正确转义的赋值语句,这些语句将分配环境变量。 Then the output from your script is eval ulated by bash.然后脚本的输出由 bash eval This is for example how eval "$(docker-machine ...)" works.例如,这是eval "$(docker-machine ...)"工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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