I have inserted python code inside bash script like this:
#!/bin/bash
echo "You are in Bash"
python <<END
# -*- coding: utf-8 -*-
import os
import sys
import getpass
print "You are in python"
username=raw_input('Bitbucket Username : ')
END
echo "Python ended"
But the problem is I am not able to take input using raw_input or input when I insert python in bash. Python alone works fine. What is the problem here in my code?
Instead of a heredoc, just user the -c parameter to pass a command:
$ python -c "username = raw_input('Enter name: ')
print 'Hello', username
"
Enter name: Chris
Hello Chris
Once you say END, you are telling bash that your program is over. Bash gives your lines as input to Python. If you are in python, type each line that you wrote there, regardless of what prompt, and when you are done, signify EOF by Ctrl-D on linux, Ctrl-Z on windows. You will see that raw_input() will have a EOFError. That is what bash is doing. It gives Python each line, and then says "We're done. Send EOF". It pays no attention to what prompt is given. It doesn't know that you are asking for input. This is a useful feature, however, because if it didn't have that, there would be nothing telling Python to exit...ever. You would have to send KeyboardInterrupt to get that program to exit.
Related
I have a python script (not created by me), let's call it myscript, which I call with several parameters.
So I run the script like this in Windows cmd:
Code:
/wherever/myscript --username=whoever /some/other/path/parameter
And then a prompt appears and I can pass arguments to the python script:
Process started successfully, blabla
Python 2.7.2 blabla
(LoggingConsole)
>>>
And I write my stuff, then quit to be back into cmd:
>>> command1()
>>> command2()
>>> quit()
I suspect some errors occurring in this part, but only once for a hundred trials. So I want to do it by a script.
I want to pipe to this script the internal command1 command2, so that I can test this function thousand times and see when it breaks. I have the following piece of code:
echo 'command1()' | py -i /wherever/myscript --username=whoever /some/other/path/parameter
This unfortunately doesn't generate the same behaviour, as if it would be manually entered.
Can I simulate this behaviour with pipes/redirecting output? Why doesn't it work? I expect that the 'command1()' text will be entered when the script waits for the commands, but it seems I'm wrong.
Thanks!
EDIT 16/02/2021 3:33PM :
I was looking for the cmd shell way to solve this, no python stuff
The piece of script
echo 'command1()' | py -i /wherever/myscript --username=whoever /some/other/path/parameter
is almost correct, just remove the '' :
echo command1() | py -i /wherever/myscript --username=whoever /some/other/path/parameter
my issues were coming from myscript. Once I fixed the weird things on this side, this part was all ok. You can even put all commands together:
echo command1();command2();quit(); | py -i /wherever/myscript --username=whoever /some/other/path/parameter
This question is adapted from a question of gplayersv the 23/08/2012 on unix.com, but the original purpose made the question not answered.
Easy to have pipes.
If you want to get the standard input :
import sys
imput = sys.stdin.read()
print(f'the standard imput was\n{imput}')
sys.stderr.write('This is an error message that will be ignored by piping')
If you want to use the standard input as argument:
echo param | xargs myprogram.py
Python's built-in fileinput module makes this simple and concise:
#!/usr/bin/env python3
import fileinput
with fileinput.input() as f:
for line in f:
print(line, end='')
Than you can accept input in whatever mechanism is easier for you:
$ ls | ./filein.py
$ ./filein.py /etc/passwd
$ ./filein.py < $(uname -r)
I have a program which needs to receive input very fast and I know what the input has to be, but there is a timer which I suppose expects no delay between opening the program and entering the input.
I've tried using bash script but it doesn't seem to work, and trying ./program; password also doesn't work (it returns that 'password' is not a command).
My bash script looks like this:
#! /bin/bash
cd ~/Downloads
./program
password
Perhaps it's working, but I'm not receiving any output from the program, which would usually display how long it took to get an input.
Well, first of all, change execution to ~/Downloads/program password. Also make sure program is executable ( chmod +x if it isn't) and that it takes arguments.
Furthermore, to refrain from mentioning the path every time, move program to ~/bin/ (create if it doesn't exist) and add that location to $PATH if it isn't there.
If the "program" does not expect the password as a command line argument, then you probably want to input it through stdin:
#! /bin/bash
cd ~/Downloads
echo "password" | ./program
or, if there is more input:
./program <<INPUT
password
moreInput
moreInput2
...
moreInputN
INPUT
The first variant uses simple piping, the second relies on HereDocs.
In the (improbable) case that the program expects the password as an argument, you have to pass it as follows:
./programm password
without line-breaks and semicolons in between.
I'm saying that this is "improbable", because if such an invokation is used from the shell, then the password will be saved as clear text in bash-history, which is obviously not very good.
I need to extend a shell script (bash). As I am much more familiar with python I want to do this by writing some lines of python code which depends on variables from the shell script. Adding an extra python file is not an option.
result=`python -c "import stuff; print('all $code in one very long line')"`
is not very readable.
I would prefer to specify my python code as a multiline string and then execute it.
Use a here-doc:
result=$(python <<EOF
import stuff
print('all $code in one very long line')
EOF
)
Tanks to this SO answer I found the answer myself:
#!/bin/bash
# some bash code
END_VALUE=10
PYTHON_CODE=$(cat <<END
# python code starts here
import math
for i in range($END_VALUE):
print(i, math.sqrt(i))
# python code ends here
END
)
# use the
res="$(python3 -c "$PYTHON_CODE")"
# continue with bash code
echo "$res"
I have a simple Python program that asks yes or no question and I validate that input.
If I run this Python shell, it runs fine. If I enter invalid characters it loops back to top of while.
However, if I run this in the terminal window and try to enter an invalid character it errors as shown below.
endProgram = 0
while endProgram != 1:
userInput = input("Yes or No? ");
userInput = userInput.lower();
while userInput not in ['yes', 'no']:
print("Try again.")
break
endProgram = userInput == 'no'
Looks like your RPi is using Python 2; the input function does an eval there.
input in Python 3 is equivalent to raw_input in Python 2. (See PEP-3111)
Ideally, you should change your RPi interpreter to Python 3. Failing that, you can make it version-agnostic like so:
try:
input = raw_input
except NameError:
pass
I can clearly see in the interactive shell you working in python 3.2.3 (background). But I can not see the python version you're running from the command line (foreground).
On your raspberrypi, execute this command from the shell:
python --version
I am expecting to see python 2.x here, because the behaviour of input() differs between python 2 and python 3, in a way that would cause exactly the behaviour you have seen.
You might want to add a line like
#!/usr/bin/env python3
To the top of your .py file, and then chmod +x on it. Afterward you should be able to execute it directly (./guipy01.py) and the correct python interpreter will be selected automatically.
This question already has answers here:
How do I read from stdin?
(25 answers)
Closed 20 days ago.
I would like to write a program that responds to inputs from the command line. Typically, I will start the program from the command line:
c:\>python my_responder.py
It will then give me a prompt:
responder> Hello. Please type your question.
responder> _
I will then type something, and hit enter:
responder> How many days are there in one week?
The responder will then reply with the result of a function (the input of which is the typed string). e.g.
def respond_to_input(input):
return 'You said: "{}". Please type something else.'.format(input)
responder> You said: "How many days are there in one week?". Please type something else.
I cannot seem to connect this kind of command line input / output to a function in python.
Additional Info: I have no understanding of stdin/stdout, and they feel relevant. I also have no understanding of how to get Python to interact with command line in general (other than running one python program that can print to the window).
Apart from raw_input() there is also the sys.argv list, (http://docs.python.org/2/tutorial/interpreter.html#argument-passing) which is pretty useful:
from __future__ import print_function # Only needed in python2.
from sys import argv as cli_args
def print_cli_args():
print(*cli_args[1:])
print_cli_args()
You would save it in a file, lets say echo.py and run it like this in the shell:
$ python2 echo.py Hello, World!
And it would print to stdout:
Hello, World!