我有一个需要使用一个命令行参数的PHP脚本。我需要从我的python脚本中调用这个脚本。
Popen('php simplepush.php "Here's the argument"', shell=True, cwd="/home/ubuntu/web/firestopapp.com/app")
^那是有效的。但是,我想在Python脚本中传递一个变量,而不是“这是参数”。但是当我尝试:
var1 = "yes"
Popen(['php', 'simplepush.php', var1], shell=True, cwd="/home/ubuntu/web/firestopapp.com/app")
它不再有效。这是通过crontab运行的,这导致我必须包含cwd参数。
我真的很感激任何帮助,似乎是一个相当直接的句法问题。
在Eric的建议之后:
Traceback (most recent call last):
File "/home/ubuntu/web/mywebsite.com/app/email_parse.py", line 25, in <module>
Popen('php simplepush.php "Here's the argument"', shell=False, cwd="/home/ubuntu/web/mywebsite.com/app")
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Sihrc的解决方案让我得到以下信息,因此它不是一个完整的解决方案。
/bin/sh: 1: cannot open my2ndemail@gmail.com: No such file
这是代码的其余部分。
#!/usr/bin/python
import email, getpass, imaplib, os, subprocess
from subprocess import Popen
detach_dir = '.'
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login("myemail@gmail.com","mypassword")
m.select('mailbox')
resp, items = m.search(None, "(UNSEEN)")
message = ""
items = items[0].split()
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_string(email_body)
message += "["+mail["From"]+"] :" + mail["Subject"] + "\n"
for part in mail.walk():
if part.get_content_type() == 'text/plain':
message += part.get_payload()
else:
continue
Popen('php simplepush.php ' + str(eval('message')), shell=True, cwd="/home/ubuntu/web/firestopapp.com/app")
答案 0 :(得分:0)
改道!躲避问题是我的专长!
var1 = "yes"
Popen('php simplepush.php ' + '"' + str(eval('var1')) + '"', shell=True, cwd="/home/ubuntu/web/firestopapp.com/app")
答案 1 :(得分:0)
#!/usr/bin/python
import email, getpass, imaplib, os, subprocess
import shlex
from subprocess import Popen
detach_dir = '.'
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login("myemail@gmail.com","mypassword")
m.select('mailbox')
resp, items = m.search(None, "(UNSEEN)")
message = ""
items = items[0].split()
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_string(email_body)
message += "["+mail["From"]+"] :" + mail["Subject"] + "\n"
for part in mail.walk():
if part.get_content_type() == 'text/plain':
message += part.get_payload()
else:
continue
for pdir in os.getenv('PATH'):
if os.access("{}/{}".format(pdir, 'php'), os.X_OK):
phppath = "{}/{}".format(pdir, 'php')
break
cmd = '{} simplepush.php "{}"'.format(phppath, message)
Popen(shlex.split(cmd),
cwd="/home/ubuntu/web/firestopapp.com/app")