简体   繁体   中英

Running bash commands from python in a single session

How do i run bash commands from python while the session is maintained. For example if I pwd, then cd .., then pwd, it SHOULD move to a directory level one level lower than the current directory . 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...).

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.
  • Use os.chdir and other methods to change the python process environment variables as needed before running each bash command.

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