向函数传递字符串参数-为什么不起作用?

2024-09-26 22:54:33 发布

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

尝试将字符串参数传递给函数,然后在整个函数中将其用作变量。因为某些原因,当我试图这样做时,它不起作用。我做错什么了?

import subprocess
def printerSetup(printer):
    subprocess.call(r'Cscript c:/windows/System32/Printing_Admin_Scripts/en-US/Prnport.vbs -a -r "'printer'.print.web.com" -h "' + printer + '.print.web.com" -o raw')
    if printer == 'saturn' or printer == 'jupiter' or printer == 'neptune':
        subprocess.call(r'rundll32 printui.dll, PrintUIEntry /if /b "' + printer + '" /f w:\printers\toshibae3511\eng\est_c2.inf /r "' + printer + '.print.web.com" /m "TOSHIBA e-STUDIO Color PS3"')
    if printer == 'mercury':
        subprocess.call(r'rundll32 printui.dll, PrintUIEntry /if /b "' + printer + '" /f w:\printers\dell1720\drivers\print\dell1720\DKABJ740.inf /r "' + printer + '.print.web.com" /m "Dell Laser Printer 1720dn"')

printerSetup("neptune")
printerSetup("mercury")

编辑了程序。尝试运行此新程序后,出现以下错误:

C:\Python27\Projects\Printer Setup>c:\python27\python.exe saturn.py
  File "saturn.py", line 3
    subprocess.call(r'Cscript c:/windows/System32/Printing_Admin_Scripts/en-US/P
rnport.vbs -a -r "'printer'.print.web.com" -h "' + printer + '.print.web.c
om" -o raw')

                         ^
SyntaxError: invalid syntax

Tags: 函数comwebifadminwindowscallprinter
1条回答
网友
1楼 · 发布于 2024-09-26 22:54:33

您需要为每个or语句指定variable == value,如下所示:

if printer == 'saturn' or printer == 'jupiter' or printer == 'neptune':

您还忘记了每个if语句的尾随冒号。

如果您想说“这个变量与这个值列表匹配吗?”,以下内容可能更适合您:

if printer in ('saturn', 'jupiter', 'neptune'):

您还需要将变量添加到字符串中-不能只将它们放在相邻的位置:

'string' + variable + 'string'

 # not

 'string'variable'string'

相关问题 更多 >

    热门问题