简体   繁体   中英

How to run bash commands from Python preferably with the os library?

I am trying to run the following python script named test.py . It contains multiple bash commands which I would like to execute in a Linux terminal (unix). This is the content of the file:

import os

os.system('echo install virtualenv')
os.system('sudo pip install virtualenv')

os.system('echo create virtual environment')
os.system('virtualenv my_virtualenvironment')

os.system('echo activate virtual environment')
os.system('source my_virtualenvironment/bin/activate')

I am running the Python script using the following in the terminal:

python3 test.py

The problem that I have is that the commands do not run the same way as they would on a Linux terminal. The output is the following error when trying to execute the last line of the Python script:

sh: 1: source: not found

The last command source my_virtualenvironment/bin/activate normally runs fine if I execute it directly in the terminal (without my Python script). Now, what does sh: 1: mean and why does it not work with my code? I would expect to get something starting with bash: .

Also I have found this solution, but I would like not to use lists for executing commands and maybe even to stick with the os library (if there is a simpler solution without os, I am also open for that): https://stackoverflow.com/a/62355400/11535508

source is a bash built-in command, not an executable.

Use the full path to the python interpreter in your commands instead of venv activation, eg os.system('<venv>/bin/python...') .

The second option is to write your commands into a separate bash script and call it from python:

os.system('bash script.sh')

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