Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute python program from command line without script file

Tags:

python

bash

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?

like image 238
patentfox Avatar asked Jun 07 '26 01:06

patentfox


1 Answers

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()
"""
like image 91
Druta Ruslan Avatar answered Jun 10 '26 06:06

Druta Ruslan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!