简体   繁体   中英

Execute python program from command line without script file

I want to execute a python program on a remote server, without creating a script. The remote server does not allow me to create any files anywhere on the file system.

The python program has following structure, though the functions are a lot more complicated

def test2():
  print("test2")

def test_func():
  test2()
  print("test_func")

test_func()

Is there a way to execute this program directly from command line?
I have tried these 2 approaches

  1. Pass the code using python -c option.
  2. Launch python interactive mode, and copy paste the code to run.

I get errors in both the cases. However, any code without user defined functions is able to execute with 2nd approach. Is it possible to get the code above working without creating a local script?

You still can use functions in approach like your first:

$ printf "def f():\n    print 'hello'\n\nf()" | python
hello

i found a solution, maybe it will help, you can use EOF

$ python << EOF
> def test2():
>   print("test2")
> 
> def test_func():
>   test2()
>   print("test_func")
> 
> test_func()
> EOF

# output
test2
test_func

You can also use python -c with """

$ python -c """
def test2():
  print("test2")

def test_func():
  test2()
  print("test_func")

test_func()
"""

If you can store your python sources on a HTTP server AND wget (or similar) is installed on the remote host

$ wget -O - http://my.server.de/some/path/my_program.py | python

could be a cheap way of accomplishing your goal.

Another possibility, no HTTP server involved, but you'll need scp or ssh on the remote host

$ scp my_host:a_python_file.py /dev/stdout | python
$ ssh my_host 'cat a_python_file.py' | python

Here are two aliases that show examples of how python -c "something here" can work for you.

The first one will show you the zen of python (to standard out)

alias zen='python -c "import this"'

The second will read it to you (TTS)

alias zen2='python -c "import this" | say'

From the man page

-c -- program passed in as string (terminates option list)

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