用参数执行python

时间:2016-07-15 16:15:44

标签: python powershell

我正在尝试调用一个Python脚本,该脚本接受在VMware中备份PostgreSQL数据库的参数。

代码是这样的:

# path to where you want to save the backup to
$filepath = "D:\pgbackups\"

# filename you want to call the backup
$filename = "torwpinf002_postgresdb_bk_"

# format the date/time so you can append to the backup filename
$filedate = get-date -Format "yyyyMMdd_HHmm"

# pack it all together 
$fullFileSave = $filepath + $filename + $filedate.ToString() + ".bak"

$BackupScriptFile = "C:\backup_win.py"

$executebackup = "`"$BackupScriptFile`"" + ' -p  "QX+qos5eu1D36&kB" -f ' + "`"$fullFileSave`""

python $executebackup

如果我抛出一个断点,我可以显示变量$executebackup,它会显示:

"C:\backup_win.py " -p  "QX+qos5eu1D36&kB" -f "D:\pgbackups\torwpinf002_postgresdb_bk_20160715_1050.bak"

这会引发错误:

python : usage: backup_win.py [-h] -p PASSWORD -f BACKUP_FILE
At C:\Program Files\VMware\vCenter Server\python\torwpinf002_pgbackup.ps1:39 char:1
+ python $executebackup
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (usage: backup_w... -f BACKUP_FILE:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

backup_win.py: error: argument -p is required

有趣的是,我运行的这个盒子是Windows 2012 R2。此SAME脚本在Windows 2008 R2上运行良好。

咦?

好吧,所以我认为正在发生的是我传递给python.exe的命令的双引号正在破坏作品,所以我改了一下:

$executebackup = $BackupScriptFile + ' -p  "QX+qos5eu1D36&kB" -f ' + $fullFileSave
如果我将它回显到屏幕上,则输出

(注意文件路径周围没有引号):

C:\backup_win.py  -p  "QX+qos5eu1D36&kB" -f D:\pgbackups\torwpinf002_postgresdb_bk_20160715_1050.bak

但是会返回此错误:

python.exe : C:\Program Files\VMware\vCenter Server\python\python.exe: can't open file 'C:\backup_win.py  -p  QX+qos5eu1D36&kB -f 
D:\pgbackups\torwpinf002_postgresdb_bk_20160715_1050': [Errno 22] Invalid argument
At line:1 char:1
+ python.exe $executebackup
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (C:\Program File...nvalid argument:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

我真的被卡住了,我确信这是一个简单的专家可以在5秒内调整..我的大脑已煮熟,我不知道下一步该尝试什么。最让我烦恼的部分是它在Windows 2008上运行良好但在2012年没有。

这是非常有趣的事情。如果我取$executebackup的输出:

C:\backup_win.py  -p  "QX+qos5eu1D36&kB" -f D:\pgbackups\torwpinf002_postgresdb_bk_20160715_1058.bak

并将其粘贴到PowerShell控制台中,它可以正常工作。

PS C:\Users\Administrator> C:\backup_win.py  -p  "QX+qos5eu1D36&kB" -f D:\pgbackups\torwpinf002_postgresdb_bk_20160715_1058.bak

Backup completed successfully.

有关如何从脚本中执行此操作的任何想法吗?

1 个答案:

答案 0 :(得分:1)

不要将命令行定义为字符串(除非您希望在大多数情况下通过Invoke-Expressionwhich I wouldn't recommend运行它)。只需使用call operator&)并将您的参数放在控制台中:

& python.exe C:\backup_win.py -p "QX+qos5eu1D36&kB" -f D:\pgbackups\torwpinf002_postgresdb_bk_20160715_1058.bak

如果你的论点有所不同,你可以将它们放在一个数组中,并在调用python.exe时将其splat

$params = 'C:\backup_win.py', '-p', "QX+qos5eu1D36&kB",
          '-f', 'D:\pgbackups\torwpinf002_postgresdb_bk_20160715_1058.bak'

& python.exe @params