python -c and `while` - python

Is there a way to loop in while if you start the script with python -c? This doesn't seem to be related to platform or python version...
Linux
[mpenning#Hotcoffee ~]$ python -c "import os;while (True): os.system('ls')"
File "<string>", line 1
import os;while (True): os.system('ls')
^
SyntaxError: invalid syntax
[mpenning#Hotcoffee ~]$
[mpenning#Hotcoffee ~]$ python -V
Python 2.6.6
[mpenning#Hotcoffee ~]$ uname -a
Linux Hotcoffee 2.6.32-5-amd64 #1 SMP Sun May 6 04:00:17 UTC 2012 x86_64 GNU/Linux
[mpenning#Hotcoffee ~]$
Windows
C:\Users\mike_pennington>python -c "import os;while True: os.system('dir')"
File "<string>", line 1
import os;while True: os.system('dir')
^
SyntaxError: invalid syntax
C:\Users\mike_pennington>python -V
Python 2.7.2
C:\Users\mike_pennington>
I have tried removing parenthesis in the while statement, but nothing seems to make this run.

python -c $'import subprocess\nwhile True: subprocess.call(["ls"])'
would work (note the $'...' and the \n).
But it could be that it only works under bash - I am not sure...

Multiline statements may not start after a statement-separating ; in Python – otherwise, there might be ambiguities about the code blocks. Simply use line breaks in stead of ;. This "works" on Linux:
$ python -c "import os
while True: os.system('ls')"
Not sure how to enter this on Windows, but why not simply write the commands to a .py file if it's more than one line?

Don't know about windows, if all you want is to be able to type in one-liners, you could consider line breaks inside quotes:
% python -c "import os;
while (True):
os.system('ls')"

If you really must do this in windows, you could use exec:
python -c "exec \"import os;\rwhile True:\r os.system('dir')\""
(I substituted dir so it works on my windows system)

Related

Running a python program stored in a shell variable

I want write a shell script that will run a Python Code stored in a shell variable $CODE.
#!/bin/bash
python3 $CODE
But this does not work, is there any way to do this? Any help is appreciated.The program that will be run:
print("Hello World")
export CODE='print("Hello World")'
Use the -c option.
python3 -c "$CODE"
python3 <<< "$CODE"
[Python.Docs]: Command line and environment - -c <command> states:
Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code.
Example:
[064bit prompt]> CODE='import sys;print("Hello World");print(sys.version)'
[064bit prompt]> python -c "${CODE}"
Hello World
3.8.10 (default, Jun 22 2022, 20:18:18)
[GCC 9.4.0]
But this comes with some limitations. I'd save the code in a script and run that instead.

Passing a shell variable to inline python in a shell script

I have a simple shell script where i want to be able to pass variables to some inline python i will write. For example like this
funny=879
echo $funny
python -c "
print(f"hello {$funny}")
"
However this prints
879
File "<string>", line 2
print(fhello
^
SyntaxError: unexpected EOF while parsing
(pipeline) $
Any thoughts on what i could be doing wrong? I know i am setting the variable correct because when i do echo it prints out the variable so it is definitely set correct but for some reason python script is not able to use it.
It's because you're using outer double quotes.
python -c "print(f"hello {$funny}")"
Gets turned into:
python -c print(fhello {879})
So python is passed 2 separate strings.
The inner double quotes would need to be escaped in order to get passed through to python.
$ funny=879; python3 -c "print(f\"hello $funny\")"
hello 879
Instead of messing around with quoting - if you export your variables you can access them from python using the os.environ dict.
$ export funny=879; python -c 'import os; print(os.environ["funny"])'
879
You can use the var=value command syntax and omit the export (note the lack of a semicolon)
$ funny=879 fonny=978 python3 -c 'import os; print(os.environ["funny"], os.environ["fonny"])'
879 978

Multiline python code execution in terminal (Windows)

As the question states, I would like to know how to execute arbitrary python code in a windows terminal (or Anaconda Prompt). Please note that I am on Windows. In general, terminal execution is something like:
>>python -c "print('Some Text to Print')"
But what happens if I have multiple lines with indents and indent-indents. Here is an example of things I have tried (please note that I am forcing two lines here in some way, the solution "for i in range(10): print(i)" is not appropriate to the question since this only has one line of python code):
>>python -c "for i in range(10):; print(i)"
>>python -c "for i in range(10):\nprint(i)"
>>python -c "for i in range(10):\n print(i)"
>>python -c "for i in range(10):\n\tprint(i)"
Now clearly I can do this:
>>python -c "exec('for i in range(10):\n\tprint(i)')"
and this solution works. But this solution feels wrong. Is there a more pythonic way? In particular, why do the newline and tab characters work for "exec()" but not for "python -c"?
Have you already tried with ^ ?
In this case if you will not be careful with spaces, you will obtain an IndentationError: unexpected inden
python -c ^
More? "for i in range(2): ^
More? print(i)"
[EDIT]
There are also another way:
python -c ^
More? "for i in range(2):^ print(i)"
0
1
^ is the EOL character used as the new line character in most other non-Unix operating systems, including Microsoft Windows and Symbian OS.
You can do
> echo "for i in range(2):
>> print(i)
>> " | python
0
1

Python syntax error when running from bash script

I've got a Python script uploaded to a linux machine, which I need to be ran through a bash script. The script runs absolutely fine when I type "python test.py", and it outputs as expected. However when I run the bash script "bash runScript.sh" I get a syntax error.
My python script (It's dead simple):
with open ("TextFiles/10.10.10.10config.txt",'r') as f:
print f
My bash script:
wget --no-check-certificate https://10.10.10.10/config.txt -O /usr/bin/grabber/TextFiles/10.10.10.10config.txt
/usr/bin/python2 /usr/bin/grabber/test.py
The error when I run the bash script states:
File "/usr/bin/grabber/test.py", line 1
with open ("TextFiles/10.87.4.4channel_config.txt",'r') as f:
^
SyntaxError: invalid syntax
Has anyone had this problem before?
Quick solution: change python2 to python2.7 in your script.
The reason, as mentioned in the comments, is that your /usr/bin/python2 is linking to an old version of python in your system.
Again and again.... I'll show you!
[server]$ /usr/local/bin/python2.7 -c "with open('test.py','r') as f: print 'OK'"
OK
[server]$ /usr/local/bin/python2.5 -c "with open('test.py','r') as f: print 'OK'"
<string>:1: Warning: 'with' will become a reserved keyword in Python 2.6
File "<string>", line 1
with open('test.py','r') as f: print 'OK'
^
SyntaxError: invalid syntax
with can be used after python 2.6

Using bash echo command to input into a python one liner

I am trying to input a string using echo into a Python one liner then perform a Caeasar's Cipher on the string.
One of the examples my instructor gave me was this.
~ $ echo "Hello Holly." | python -c "import sys; [print(line) for line in sys.stdin]"
The output is suppose to be: Hello Holly.
How ever when I type the command in I get:
File "<string>", line 1
import sys; [print(line) for line in sys.stdin]
^
SyntaxError: invalid syntax
I would appreciate it if someone could point out the error to me. I am using Python 2.6 on Centos 6.
Thanks.
In Python 2 print is a statement, not a function. Try this instead:
echo "Hello Holly." | python -c "import sys; print [line for line in sys.stdin]"
Alternatively, you could use the following to just print plain text (thanks #mgilson):
echo "Hello Holly." | python -c "import sys; print ' '.join([line for line in sys.stdin])"
It looks like you are using python2 while your isntructor is using python 3.

Categories

Resources