简体   繁体   English

在单个会话中从python运行bash命令

[英]Running bash commands from python in a single session

How do i run bash commands from python while the session is maintained. 在维护会话的同时,如何从python运行bash命令。 For example if I pwd, then cd .., then pwd, it SHOULD move to a directory level one level lower than the current directory . 例如,如果我先输入密码,然后再输入cd ..,再输入密码,它应该移动到比当前目录低一级的目录级别。 I dont want to run all these commands as a single command with | 我不想使用|作为单个命令运行所有这些命令。 or &. 要么 &。 I want to run them on individual lines. 我想逐行运行它们。

In general, processes can't modify the environment of their parent process, or any other existing process. 通常,流程无法修改其父流程或任何其他现有流程的环境。 So you can't do this easily in the way you're describing, unless you deliberately save the environment from the child process somehow (eg end all your bash commands by redirecting env to a file, prefixing each entry in the file with export , and source that file at that at the start of every subsequent command...). 因此,除非您以某种方式故意将环境从子进程中保存下来(例如,通过将env重定向到文件,在文件中的每个条目前加上export ,并在每个后续命令的开始处从该文件中获取该文件...)。

Alternatives: 备择方案:

  • Add all of your inter-dependent bash commands to a single bash script and run the bash script from python, rather than running bash commands in python one by one. 将所有相互依赖的bash命令添加到单个 bash脚本中,然后从python运行bash脚本,而不是一个一个地在python中运行bash命令。
  • Use os.chdir and other methods to change the python process environment variables as needed before running each bash command. 在运行每个bash命令之前,请根据需要使用os.chdir和其他方法来更改python进程环境变量。

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

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