简体   繁体   中英

How to run multple lines of python code from shell, instead of from a script

I want to run python code from the shell instead of from a script.

I searched everywhere and found suggestions about using echo or Shift+Enter and using ^ at the end of the line, but ^ and shift+Enter didn't work in python shell, and I need to if there is a way to separate commands in the shell.

For example I need to run this from python shell instead of from a script:

If x > y
   print ("x is greater than y.")

but non of the options I tried worked.

You need to use : to issue a line separator.

ie

if x > y:
   print ("x is greater than y.")

If you are asking how to enter Python code in your shell, then try something like

python -c 'if x > y:
    print(("x is greater than y")'

assuming you are using a Bourne-compatible shell (Linux etc). This has the major drawback that your Python code cannot easily contain a single quote (though if you know the quoting rules of the shell it's of course not impossible or even unobvious how to create an expression which evaluates to a single quote).

However, the common way to do this (and perhaps the only way on Windows?) is to type the Python code into a file and then run it with

python filename.py

where filename.py is the name of the file where you saved your Python code.

You can of course run simply

python

to enter the Python interpreter in interactive mode, where you can type in Python expressions and have them evaluated immediately. When you type an expression which ends with a colon, Python changes the prompt from >>> to ... to indicate that it expects one or more indented lines. (Type just a newline immediately at the ... prompt to exit this mode.)

If you're just looking for a newline in the print statement, just add a \n

Ie

If x > y
   print ("x is greater than y.\n")

or...

If x > y
   print ("x is greater than y.", end="\n")

If you're not talking about inserting a newline in the print, you'll need to clarify in the OP.

Shift + enter generally works for python shell, idle, command prompt etc. If you are using some other IDE, you should search for that IDE specifically. If there is a syntax error then you will get an error message even with shift+enter.

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