Execute python command from bash

Using Python in a Bash Script [duplicate]

If I try to start python in a bash script, the script will stop running and no commands will execute after «Python» is called. In this simple example, «TESTPRINT» will not be printed. It seems like the script just stops.

#!/bin/bash python print("TESTPRINT") Echo 

How do I make the script continue running after going into Python? I believe I had the same problem a few years ago after writing a script that first needed to shell into an Android Phone. I can’t remember how I fixed it that time.

Note, python may call python2 by default on some distributions. It is often best to be safe and explicitly call python3.

4 Answers 4

To run a set of Python commands from a bash script, you must give the Python interpreter the commands to run, either from a file (Python script) that you create in the script, as in

#!/bin/bash -e # Create script as "script.py" cat >script.py  

(this creates a new file called script.py or overwrites that file if it already exists, and then instructs Python to run it; it is then deleted)

. or directly via some form of redirection, for example a here-document:

What this does is running python - which instructs the Python interpreter to read the script from standard input. The shell then sends the text of the Python script (delimited by END_SCRIPT in the shell script) to the Python process' standard input stream.

Note that the two bits of code above are subtly different in that the second script's Python process has its standard input connected to the script that it's reading, while the first script's Python process is free to read data other than the script from standard input. This matters if your Python code reads from standard input.

Python can also take a set of commands from the command line directly with its -c option:

#!/bin/bash python -c 'print("TESTPRINT")' 

What you can't do is to "switch to Python" in the middle of a bash script.

The commands in a script is executed by bash one after the other, and while a command is executing, the script itself waits for it to terminate (if it's not a background job).

This means that your original script would start Python in interactive mode, temporarily suspending the execution of the bash script until the Python process terminates. The script would then try to execute print("TESTPRINT") as a shell command.

It's a similar issue with using ssh like this in a script:

(which may possibly be similar to what you say you tried a few years ago).

This would not connect to the remote system and run the cd and ls commands there. It would start an interactive shell on the remote system, and once that shell has terminated (giving control back to the script), cd and ls would be run locally.

Instead, to execute the commands on a remote machine, use

(This is a lame example, but you may get the point).

The below example shows how you may actually do what you propose. It comes with several warning label and caveats though, and you should never ever write code like this (because it's obfuscated and therefore unmaintainable and, dare I say it, downright bad).

What happens here is that the script is being run by sh -s . The -s option to sh (and to bash ) tells the shell to execute the shell script arriving over the standard input stream.

The script then starts python - , which tells Python to run whatever comes in over the standard input stream. The next thing on that stream, since it's inherited from sh -s by Python (and therefore connected to our script text file), is the Python command print("TESTPRINT") .

The Python interpreter would then continue reading and executing commands from the script file until it runs out or executes the Python command exit() .

Источник

How to include python script inside a bash script

I need to include below python script inside a bash script. If the bash script end success, I need to execute the below script:

#!/usr/bin/python from smtplib import SMTP import datetime debuglevel = 0 smtp = SMTP() smtp.set_debuglevel(debuglevel) smtp.connect('192.168.75.1', 25) smtp.login('my_mail', 'mail_passwd') from_addr = "My Name " to_addr = " 

7 Answers 7

Just pass a HereDoc to python - .

From python help python -h :

#!/bin/bash MYSTRING="Do something in bash" echo $MYSTRING python -  

I don't see why this was downvoted. It's a simple and workable solution for some cases. It does have the (major) limitation that you can't use standard input in the python script, though (since it's receiving stdin from the heredoc).

Upvoted this answer because (unlike the accepted answer) it doesn't write the script to the file system.

look at my answer. I used the -c argument, not - . Note also that this is not very efficient, because the program is read and compiled line by line as it runs

@HuwWalters For older bash relesaes, here-documents are saved to a temporary file. For newer releases after 5.1 ("bash-5.2-rc1" or newer (2022)), if the compatibility level of the shell is 50 or lower, or if the size of the here-document is larger than the pipe buffer size of the system, the here-document is saved to a temporary file.

You can use heredoc if you want to keep the source of both bash and python scripts together. For example, say the following are the contents of a file called pyinbash.sh :

#!/bin/bash echo "Executing a bash statement" export bashvar=100 cat pyscript.py #!/usr/bin/python import subprocess print 'Hello python' subprocess.call(["echo","$bashvar"]) EOF chmod 755 pyscript.py ./pyscript.py 

Now running pyinbash.sh will yield:

$ chmod 755 pyinbash.sh $ ./pyinbash.sh Executing a bash statement Hello python 100 

Per OP's comment to another answer, I updated my answer which takes care of bash variables in the python script.

I replace subprocess.call(["echo","\$bashvar"]) into subprocess.call(["echo","bashvar"]) now it's working.

As shown (but not explained) in a couple of other answers, and as documented in the Python 3.11.1 documentation Command line and environment, you can use -c command :

In other words, you can put your entire Python script into a Bash string. Here’s a slightly complicated / convoluted approach, using command substitution and a here document:

#!/bin/bash python3 -c "$(cat ') print('you typed', a) print('\033[1;32mbye. \033[m') EOF )" 

This works. The $() (command substitution) passes the output of the command inside (in this case cat ) as the argument to Python. There is no pipelining so standard input can be used in the Python code.

This simpler approach (making the Python script a literal string) also works:

#!/bin/bash python3 -c " a = input('?>') print('you typed', a) print('\033[1;32mbye. \033[m')" 

This has the usual issue with double-quoted strings in Bash: shell meta-characters " , $ , ` and \ need to be escaped. For example, if you need to use " in your Python code, you should escape it like this:

#!/bin/bash python3 -c " a = input('?>') print(\"you typed\", a) print(\"\033[1;32mbye. \033[m\")" 

But why not just change all the single quotes in your Python code to double quotes, and put the entire Python script into single quotes?

#!/bin/bash python3 -c ' a = input("?>") print("you typed", a) print("\033[1;32mbye. \033[m")' 
$ python3 -c "print('An odd string:', '$((6*7))')" An odd string: 42 $ python3 -c 'print("An odd string:", "$((6*7))")' An odd string: $((6*7)) 

This is old question, but maybe useful for someone. It's a way to include Python script inside a Bash script and use sys.stdin .

Extract Python script and run it with -c . The trick is to use a function, that allows use ' and " in the script. Also sys.stdin is available.

#!/bin/bash read_file() < local name="$" # escape name for sed regex sed -En '/^#---=== '"$name"' ===---$/,$ ' "$0" > echo Johny | python3 -c "$(read_file script.py)" exit #---=== script.py ===--- import sys print('Your name is', sys.stdin.readline().strip()) #---===--- 

Explanation

Bash parse and execute a script line by line (command by command). It allows to put anything after exit , even binary data.

There is a file-system section in our case there. Line starting with #---=== are detected by the sed regular expression. The file content between the lines are printed out. and used as a script in Python with -c .

It's possible to put many files between #---=== patterns.

Details
  1. Python execute code from a -c argument.
  2. There is shell substitution used, $() executes command and put its stdout as a text.
  3. The read_file function takes a filename as the first argument.
  4. $ replaces all dots in the filename and next the replaced filename is put into local variable name
  5. Dot ( . ) means any character in a regular expression, [] is a list od characters, than [.] means a dot literally.
  6. sed is a stream text editor, there is used:
    • -E – use extended regular expressions in the script
    • -n – suppress automatic printing of pattern space
  7. Sed operates on the same script file $0 , it's way we can use only one file.
  8. Sed takes lines by range command ( PAT,PAT )
    • starting from regex /…/ ( #---=== with the filename and ===--- )
    • to the end of the script $
    • note: whole script command is quoted, but an apostrophe ' suppress $VAR substitution, then there are more quotations '. '"$name"'. ' .
  9. Next are set of command to work on the lines range , separated by semicolon ;
  10. First line from the lines range is skipped ( n like next), there is #---=== FILENAME ===--- line. The same pattern is used in // .
  11. If there is another #---=== line ( // ) it means the next file section in the script, than the command q (lik quit) is used. This trick allows as to use end of file ( $ ) in the line range pattern.
  12. Just print a line with command p . All printed lines are after #---=== FILENAME ===--- and before next #---===
  13. Ale printed lines from sed command are executed in the Python.

Источник

Как запустить небольшой код Python в Bash

Bash — это не только и даже не столько встроенные функции оболочки сколько программы (утилиты) командной строки. Запуская эти команды и передавая полученные данные конвейеру (по трубе) можно автоматизировать самые различные вещи, на программирование которых в других языках программирования может понадобиться очень много усилий.

Эта заметка расскажет, как запустить код Python в Bash, а также как в скрипте Bash запустить выполнение программы на Python

Как выполнить код Python в Bash

В командной строке Bash для выполнения кода используйте конструкцию вида:

Ещё один вариант, который может пригодиться в более экзотических обстоятельствах:

bash -c 'python -c "print (\"КОД\")"'
bash -c 'python -c "print (\"It works\")"'

Как в скрипте Bash запустить программу на Python

Для выполнения программы Python в скрипте Bash используйте команду вида:

python СКРИПТ.py АРГУМЕНТ1 АРГУМЕНТ2 АРГУМЕНТ3

Пример запуска скрипта extractor.py с передачей ему двух аргументов: значение переменной $line и 8080:

python extractor.py $line 8080

Как в скрипте Bash запустить программу на Python и присвоить её вывод переменной

Если вам нужно запустить скрипт Python, а затем вывод программы присвоить переменной Bash, то используйте конструкцию вида:

ПЕРЕМЕННАЯ=`python СКРИПТ.py АРГУМЕНТ1 АРГУМЕНТ2 АРГУМЕНТ3`
response=`python extractor.py $line 8080 2>/dev/null | sed -E "s/\/\/.+:/\/\/$line:/"`

Как в скрипт Bash встроить код Python

Если код Python невозможно использовать в одной строке и вы не хотите использовать для вызова внешний скрипт, тогда вам подойдёт следующая конструкция:

Там где КОД вставьте код Python.

Данный пример является рабочим:

#!/bin/bash value="I will be in the script!" script=`cat 

Ещё один вариант этой конструкции:

И ещё один вариант, в котором вывод присваивается в качестве значения переменной ABC:

Источник

Читайте также:  Python temp file path
Оцените статью