如何将python脚本加载到内存中并像命令行一样执行它?

2024-05-16 09:08:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将第三方python脚本加载到内存中,然后像在命令行中一样执行它,类似于在PowerShell中执行iex(new-object net.webclient).downloadstring("http://<my ip>/myscript.ps1")然后调用它。在

例如,我希望我的测试.py然后在web服务器上本地下载并使用命令行开关在内存中执行,类似于:

load("http://<ip>/test.py")
exec("test.py -arg1 value -arg2 value")

我很感激这是相当天真,但任何帮助都是感激的,谢谢!在


Tags: 内存命令行pytestip脚本httpnew
2条回答

我建议您使用请求下载脚本,然后使用exec执行它。在

像这样:

import requests
url="https://gist.githubusercontent.com/mosbth/b274bd08aab0ed0f9521/raw/52ed0bf390384f7253a37c88c1caf55886b83902/hello.py"
r=requests.get(url)
script=r.text
exec(script)

资料来源:

Why is Python's eval() rejecting this multiline string, and how can I fix it?

https://www.programiz.com/python-programming/methods/built-in/exec

http://docs.python-requests.org/en/master/


如果要为下载的脚本指定参数,可以执行以下操作:

^{pr2}$

要点:

import sys

class Example(object):
    def run(self):
        for arg in sys.argv:
            print arg
if __name__ == '__main__':
    Example().run()

资料来源:

https://stackoverflow.com/a/14905087/10902809

下面是一种利用Python解释器的-c选项的方法:

>>> import subprocess
>>> pycode = """
... import sys
... if sys.argv[1] == 'foo':
...     print('bar')
... else:
...     print('unrecognized arg')
... """
>>> result = subprocess.run(['python', '-c', pycode, 'bar'], stdout=subprocess.PIPE)
>>> print(result.stdout.decode())
unrecognized arg

>>> result = subprocess.run(['python', '-c', pycode, 'foo'], stdout=subprocess.PIPE)
>>> print(result.stdout.decode())
bar

这可能会带来一些问题,比如某些平台限制了作为参数传递的内容的大小。我试图使用stdin来实现这一点,Python解释器将接受它,但是它不会接受参数!在

相关问题 更多 >