Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python automation
#2
If the code is coming from an untrusted source (ie: anyone on the internet can send random python code for you to run), you should run that code in a way that won't jeopardize the system it's running on. Either within a docker container, a chroot jail, a virtual machine you can just restart after the code's run to undo whatever changes it made, etc.

As to how you'd actually run it, compile() is a builtin function that compiles a string into a code object/ast, which you can then pass to exec().

Just make sure you pass empty dicts to exec() for globals() and locals...
>>> code = '''
... for i in range(2):
...     code = 'print("new code")'
...     print(i)
... '''
>>> block = compile(code, '<string>', 'exec')
>>> block
<code object <module> at 0x000001C7A2AC4A80, file "<string>", line 2>
>>> code
'\nfor i in range(2):\n    code = \'print("new code")\'\n    print(i)\n'
>>> exec(block)
0
1
>>> code
'print("new code")'
>>> # !!! the code body was overwritten by the dynamic code
>>> code = '''
... for i in range(2):
...     code = 'print("new code")'
...     print(i)
... '''
>>> # for a little more protection, pass empty globals and locals
>>> exec(block, {}, {})
0
1
>>> code
'\nfor i in range(2):\n    code = \'print("new code")\'\n    print(i)\n'
Reply


Messages In This Thread
python automation - by newcode - Feb-04-2021, 11:14 AM
RE: python automation - by nilamo - Feb-04-2021, 08:37 PM
RE: python automation - by newcode - Feb-05-2021, 03:57 AM
RE: python automation - by nilamo - Feb-05-2021, 04:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Automation of GUI by python function dghosal 4 1,847 Aug-18-2023, 10:23 AM
Last Post: dghosal
  home automation using python barryjo 1 1,885 Jul-24-2022, 09:09 PM
Last Post: Larz60+
  Python Help, New User, Computer Automation hexagonalyeti 2 2,300 Jun-25-2021, 11:43 AM
Last Post: hexagonalyeti
  Automation using python Santhosh_Sangar 0 2,044 Mar-11-2020, 01:04 AM
Last Post: Santhosh_Sangar
  loop in pyautogui (python automation GUI application) pyprogrammer 0 5,506 Feb-12-2020, 02:52 PM
Last Post: pyprogrammer
  Python Based Data QA Automation tool suggestion Sonia567 1 2,597 Nov-19-2019, 04:46 PM
Last Post: Larz60+
  Create hybrid automation framework using python. janeho 2 3,061 Mar-20-2019, 05:27 PM
Last Post: DeaD_EyE
  Python automation GET/POST/REQUEST Raki 1 3,608 Sep-22-2017, 06:24 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020