Python操作系统带2个变量和zip

2024-07-03 06:47:25 发布

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

Sry,我的英语水平很低。在

我的问题是:

我要用“启动EXE”操作系统“功能。 它起作用了。。。在

os.system("Engine\\2.75\\python\\python.exe TEST_GUI.py")

所以…现在。这段代码启动pythonexe并启动我的测试GUI。 但是当“测试”时该怎么办图形用户界面.py“在ZIP文件中?在

我想开始Python.exe带着“测试GUI.py". 我以前不想提取压缩文件。在


Tags: 文件代码pytest功能osguizip
2条回答

您可以从zip文件导入Python模块,就像它是一个目录一样。在

例如,如果您在TEST_GUI.zip内有TEST_GUI.py(只有一个文件,没有文件夹-最简单的情况):

def main():
    print('Hello world!')

您可以使用单个shell调用调用它,如下所示:

^{pr2}$

让我逐行解释:

  • python -c-用一段代码作为参数调用Python
  • import sys;import os;-导入必要的包
  • sys.path.append(os.path.abspath('TEST_GUI.zip'))-这就是魔法发生的地方。ZIP文件可以像普通文件夹一样添加到PATH中!在
  • ^{Python现在看到了PATH环境变量,我们可以导入它。在
  • TEST_GUI.main()-我们调用main()函数,它可以做任何我们想做的事情。在

对同一个脚本使用os.system很简单:

>>> os.system("python -c \"import sys;import os;sys.path.append(os.path.abspath('TEST_GUI.zip'));import TEST_GUI; TEST_GUI.main()\"")
Hello world!
0

但是,我建议您去掉os.system,改用{a1}。在

这可以通过包含

__main__.py 

作为程序入口点的zip存档文件。比如说创建文件.py包含:

^{pr2}$

以及

__main__.py

包含:

from createfile import *

writefile('test1.txt')

然后,把它们放进去之后写文件.zip,正在运行

os.system('python writefile.zip')

导致在当前工作目录中创建test1.txt,并将“hello world”写入其中。在

在IPython中显示:

%ls
 Directory of C:\Users\tn\Documents\python\tmp

09/22/2015  11:02 PM    <DIR>          .
09/22/2015  11:02 PM    <DIR>          ..
09/22/2015  10:51 PM                52 __main__.py
09/22/2015  10:50 PM                98 createfile.py
09/22/2015  10:51 PM               422 writefile.zip
           3 File(s)            572 bytes
           2 Dir(s)  304,887,132,160 bytes free

os.system('python writefile.zip')
Out[29]: 0

%ls
 Directory of C:\Users\tn\Documents\python\tmp

09/22/2015  11:02 PM    <DIR>          .
09/22/2015  11:02 PM    <DIR>          ..
09/22/2015  10:51 PM                52 __main__.py
09/22/2015  10:50 PM                98 createfile.py
09/22/2015  11:02 PM                11 test1.txt
09/22/2015  10:51 PM               422 writefile.zip
               4 File(s)            583 bytes
               2 Dir(s)  304,887,132,160 bytes free

!type test1.txt # 'type' is the Windows equivilant of the Linux cat command
hello world

!type createfile.py

def writefile(f):
    fout = open(f, 'wt')
    fout.write('hello world')
    fout.close()

!type __main__.py
from createfile import *

writefile('test1.txt')

!7za l writefile.zip

7-Zip (A) 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18

Listing archive: writefile.zip

 
Path = writefile.zip
Type = zip
Physical Size = 422

   Date      Time    Attr         Size   Compressed  Name
         -   -                            
2015-09-22 22:50:13 ....A           98           76  createfile.py
2015-09-22 22:51:08 ....A           52           52  __main__.py
         -   -                            
                                   150          128  2 files, 0 folders

相关问题 更多 >