简体   繁体   English

使用 python 子进程运行 bash 命令

[英]Running bash command with python subprocess

I have a command in my bash_profile such as id=12345 which I defined the following alias我的 bash_profile 中有一个命令,例如id=12345我定义了以下别名

alias obs="echo $id" since the id will chance over time. alias obs="echo $id"因为 id 会随着时间的推移而出现。

Now what I want to do is call this alias in my python script for different purposes.现在我想做的是在我的 python 脚本中为不同的目的调用这个别名。 My default shell is bash so I have tried the following based on the suggestions on the web我的默认 shell 是 bash 所以我根据 web 上的建议尝试了以下操作

import subprocess

subprocess.call('obs', shell=True, executable='/bin/bash')

subprocess.call(['/bin/bash', '-i', '-c', obs])

subprocess.Popen('obs', shell=True,executable='/bin/bash')

subprocess.Popen(['/bin/bash', '-c','-i', obs])

However, none of them seems to work!但是,它们似乎都不起作用! What am I doing wrong!我究竟做错了什么!

.bash_profile is not read by Popen and friends. .bash_profile不被Popen和朋友读取。

Environment variables are available for your script, though (via os.environ ).不过,环境变量可用于您的脚本(通过os.environ )。

You can use export in your Bash shell to export a value as an environment variable, or use env :您可以在 Bash shell 中使用export将值导出为环境变量,或使用env

export MY_SPECIAL_VALUE=12345
python -c "import os; print(os.environ['MY_SPECIAL_VALUE'])"
# or
env MY_SPECIAL_VALUE=12345 python -c "import os; print(os.environ['MY_SPECIAL_VALUE'])"

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

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