3

我有 python 代码,它将下载.war文件并将其放在变量指定的路径中path

现在我想从那场战争中提取一个特定的文件到一个特定的文件夹。

但我在这里被打动了:

os.system(jar -xvf /*how to give the path varible here*/  js/pay.js)

我不确定如何将变量传递pathos.system命令。

我对python很陌生,请帮助我。

4

3 回答 3

5

如果你真的想使用os.system,shell 命令行作为字符串传递,你可以传递任何你想要的字符串。所以:

os.system('jar -xvf "' + pathvariable + '" js/pay.js)

或者您可以使用{}%s格式化等。

但是,您可能不想使用os.system.

首先,如果您想运行其他程序,使用该subprocess模块几乎总是更好。例如:

subprocess.check_call(['jar', '-xvf', pathvariable, 'js/pay.js'])

如您所见,您可以传递参数列表,而不是尝试找出如何将字符串放在一起(并处理转义和引用以及所有这些混乱)。还有许多其他优点,主要在文档本身中进行了描述。

However, you probably don't want to run the war tool at all. As jimhark says, a WAR file is just a special kind of JAR file, which is just a special kind of ZIP file. For creating them, you generally want to use JAR/WAR-specific tools (you need to verify the layout, make sure the manifest is the first entry in the ZIP directory, take care of the package signature, etc.), but for expanding them, any ZIP tool will work. And Python has ZIP support built in. What you want to do is probably as simple as this:

import zipfile
with zipfile.ZipFile(pathvariable, 'r') as zf:
    zf.extract('js/pay.js', destinationpathvariable)

IIRC, you can only directly use ZipFile in a with statement in 2.7 and 3.2+, so if you're on, say, 2.6 or 3.1, you have to do it indirectly:

from contextlib import closing
import zipfile
with closing(zipfile.ZipFile(pathvariable, 'r')) as zf:
    zf.extract('js/pay.js', destinationpathvariable)

Or, if this is just a quick&dirty script that quits as soon as it's done, you can get away with:

import zipfile
zf = zipfile.ZipFile(pathvariable, 'r')
zf.extract('js/pay.js', destinationpathvariable)

But I try to always use with statements whenever possible, because it's a good habit to have.

于 2012-12-10T09:34:33.430 回答
3

war文件不是一种zip文件吗?Python 具有zipfile支持(单击文档页面的链接)。

于 2012-12-10T09:27:01.320 回答
0

您可以使用 os.environ,它包含所有环境变量。它是一个字典,所以你可以像这样使用它:

pypath = os.environ['PYTHONPATH']

现在,如果您的意思是它是一个常见的 python 变量,只需像这样使用它:

var1 = 'pause'
os.system('@echo & %s' % var1)
于 2012-12-10T09:27:51.770 回答